我希望在我的服务器上实现一个套接字监听器控制台应用程序,它从多个套接字客户端获取数据。
另一方面,每个客户端都有自己的域名(不使用IP地址)。我使用静态IP地址在服务器上运行侦听器,并将通配符DNS记录定义为IP地址(如:*.xxx.yyy.com)。
当我平移域名时,静态IP地址被解析,客户端能够使用域名发送数据。
我正在特定端口上测试一个简单的TCP侦听器控制台应用程序,以获取由我的控制台客户端发送的数据。
下面是示例侦听器代码:
using System;
using System.Net;
using System.Text;
using System.Net.Sockets;
namespace SocketExample
{
public class SocketListener
{
public static int Main(String[] args)
{
StartServer();
return 0;
}
public static void StartServer()
{
var ipAddress = IPAddress.Parse("xxx.xxx.xxx.xxx");
IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000);
try
{
Socket listener = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
listener.Bind(localEndPoint);
listener.Listen(10);
Socket handler = listener.Accept();
string data = null;
byte[] bytes = null;
while (true)
{
bytes = new byte[1024];
int bytesRec = handler.Receive(bytes);
data += Encoding.ASCII.GetString(bytes, 0, bytesRec);
if (data.IndexOf("<EOF>") > -1)
{
break;
}
}
Console.WriteLine("Text received : {0}", data);
byte[] msg = Encoding.ASCII.GetBytes(data);
handler.Send(msg);
handler.Shutdown(SocketShutdown.Both);
handler.Close();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
Console.WriteLine("\n Press any key to continue...");
Console.ReadKey();
}
}
}客户端代码是:
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
namespace Client
{
public class SocketClient
{
public static void Main(String[] args)
{
byte[] bytes = new byte[1024];
var ipAddress = IPAddress.Parse("xxx.xxx.xxx.xxx");
IPEndPoint remoteEP = new IPEndPoint(ipAddress, 11000);
Socket sender = new Socket(ipAddress.AddressFamily,
SocketType.Stream, ProtocolType.Tcp);
sender.Connect(remoteEP);
Console.WriteLine("Socket connected to {0}", sender.RemoteEndPoint.ToString());
byte[] msg = Encoding.ASCII.GetBytes("This is a test<EOF>");
int bytesSent = sender.Send(msg);
int bytesRec = sender.Receive(bytes);
Console.WriteLine("Echoed test = {0}", Encoding.ASCII.GetString(bytes, 0, bytesRec));
sender.Shutdown(SocketShutdown.Both);
sender.Close();
}
}
}使用DNSEntry也很好,但问题是我想根据他们调用的域名来识别我的客户端。
例如,我有两个客户:
当侦听器接收到数据时,我希望根据调用的域名标识客户端。
我想知道如何在侦听器端解析调用的域名。是否可以获得域名,或者客户端应该在发送的数据中发送特定的域名?
发布于 2019-06-27 22:31:24
如果您想要客户端用来连接的文本域名,那么您的客户端必须将其作为其数据协议的一部分发送到服务器,类似于HTTP中有一个Host:头
在进行套接字连接时,只使用IP地址进行连接。文本域名在那时已经不存在了。
https://stackoverflow.com/questions/56798909
复制相似问题