Unity and winform use socket communication
Download Demo address: Unity communicates with winformsocket
1. In unity
- Unity acts as a server to receive messages from winform. It needs to establish a server first and wait for the client to connect.
private void SocketConnet()
{
//if (_ClientSocket != null)
// _ClientSocket.Close();
//控制台输出侦听状态;
Debug.Log("Waiting for a client");
_ClientSocket = _ServerSocket.Accept();
//获取客户端的IP和端口;
IPEndPoint ipEndClient = _ClientSocket.RemoteEndPoint as IPEndPoint;
//输出客户端的IP和端口
Debug.Log("Connect with" + ipEndClient.Address.ToString() + ":" + ipEndClient.Port.ToString());
//连接成功发送数据;
_SendStr = "Connect succeed";
SocketSend(_SendStr);
Thread th = new Thread(ReceiveMsg);
th.IsBackground = true;
th.Start(_ClientSocket);
}
- Unity receives message processing
private void ReceiveMsg(object o)
{
Socket client = o as Socket;
while (true)
{
try
{
byte[] buff = new byte[1024];
int len = client.Receive(buff);
string msg = Encoding.UTF8.GetString(buff, 0, len);
print("收到客户端" + client.RemoteEndPoint.ToString() + "的信息:" + msg);
DataManager._DM.numData = msg.Split(' ');
SocketSend(_SendStr);
}
catch (System.Exception ex)
{
SocketSend(ex.ToString());
break;
}
}
}
- DataManager is a singleton used to store received data
2. In winform
- First connect to the server
//定义一个套接字监听
socketclient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//获取文本框中的IP地址
IPAddress address = IPAddress.Parse("127.0.0.1");
//将获取的IP地址和端口号绑定在网络节点上
IPEndPoint point = new IPEndPoint(address, 7000);
try
{
//客户端套接字连接到网络节点上,用的是Connect
socketclient.Connect(point);
}
catch (Exception ex)
{
return;
}
threadclient = new Thread(recv);
threadclient.IsBackground = true;
threadclient.Start();
- send data to server
void ClientSendMsg(string sendMsg)
{
//将输入的内容字符串转换为机器可以识别的字节数组
byte[] arrClientSendMsg = Encoding.UTF8.GetBytes(sendMsg);
//调用客户端套接字发送字节数组
socketclient.Send(arrClientSendMsg);
}
Download Demo address: Unity communicates with winformsocket