unity与winform 使用socket通信
下载Demo地址:unity与winformsocket通信
一. 在unity中
- unity作为服务端,接收winform发来的消息,需要先建立服务端,等待客户端连接
private void SocketConnet()
{
Debug.Log("Waiting for a client");
_ClientSocket = _ServerSocket.Accept();
IPEndPoint ipEndClient = _ClientSocket.RemoteEndPoint as IPEndPoint;
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接收消息处理
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是一个单例,用来存储接收到的数据

二. 在winform中
- 首先连接服务端
socketclient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPAddress address = IPAddress.Parse("127.0.0.1");
IPEndPoint point = new IPEndPoint(address, 7000);
try
{
socketclient.Connect(point);
}
catch (Exception ex)
{
return;
}
threadclient = new Thread(recv);
threadclient.IsBackground = true;
threadclient.Start();
- 发送数据到服务端
void ClientSendMsg(string sendMsg)
{
byte[] arrClientSendMsg = Encoding.UTF8.GetBytes(sendMsg);
socketclient.Send(arrClientSendMsg);
}
下载Demo地址:unity与winformsocket通信
|