TCP通讯中:客户端如何指定软件的本地端口号?
最近在Socket 通讯中用 Socket完成了对客户端 接收服务端信息以及 往服务端发送信息的功能。具体方法介绍如下:
通过Load方法 加载到指定的服务端口(IP+Port)
class SocketClient
{
public static readonly SocketClient Current = new SocketClient();
Thread threadClient = null;
Socket socketClient = null;
private string _ip = string.Empty;
// 1: 加载socket
public void Load(string ip, int port)
{
try
{
this._ip = ip;
this._port = port;
socketClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
IPAddress address = IPAddress.Parse(_ip);
// 将获取的Ip地址和端口绑定在网络节点上
IPEndPoint iPEndPoint = new IPEndPoint(address, _port);
// 客户端socket 连接到网络节点上,用Connect
socketClient.Connect(iPEndPoint);
int clientPort = (socketClient.LocalEndPoint as IPEndPoint).Port;
int remotePort = (socketClient.RemoteEndPoint as IPEndPoint).Port;
threadClient = new Thread(SocketDataReceived);
threadClient.IsBackground = true;
threadClient.Start();
}
}
// 2 消息接收
void SocketDataReceived()
{
try
{
if (socketClient == null)
{
return;
}
// 持续监听服务端发来的消息
while (true)
{
byte[] arrRecvmsg = new byte[1024 * 1024 * 2];
int length = socketClient.Receive(arrRecvmsg);
string strRevMsg = Encoding.UTF8.GetString(arrRecvmsg, 0, length);
if (strRevMsg.Contains("[RC]"))
{
ExportFoxconnShopfloor_JCManager.Current.ControlCMDRevMsg.Add(strRevMsg);
}
}
}
}
// 消息发送
public void SocketWriteData(string sendMsg)
{
List<byte> sendLbyte = new List<byte>();
sendLbyte = Encoding.UTF8.GetBytes(sendMsg).ToList<byte>();
socketClient.Send(sendLbyte.ToArray(), SocketFlags.None);
}
}
以上完成了对 客户端socket的设置:
此时的客户端绑定的是服务器的端口,并没有为自己设计一个显示的端口,这样会出现一个问题: 当多个客户端连接同一个服务器的时候,服务器往指定的客户端输出
信息的时候会因为不知道客户的本地端口而无法往指定的端口输出信息,因此需要在创建客户端的时候指定客户端的端口号和IP,
具体方法如下:
在类中添加一个 TcpClient 的对象:
TcpClient tcpClient = null;
在创建Load 的时候:
并不直接去创建 socket , 而是采用如下方式:
//设置本地端口
// IP 为 IPAddress.Any 设置本地端口 5001
tcpClient = new TcpClient(new IPEndPoint(IPAddress.Any, 5001));
// 连接服务器
tcpClient.Connect(iPEndPoint);
socketClient = tcpClient.Client; // 设置 socket 用于接收和发送消息
int clientPort = (socketClient.LocalEndPoint as IPEndPoint).Port; // 本地端口获取
int remotePort = (socketClient.RemoteEndPoint as IPEndPoint).Port; // 服务端端口获取
这样就可以自定义 客户端的端口号和IP 方便 服务端发送信息。