欢迎加入Unity业内qq交流群:956187480



Udp是没有绝对的c/s观念的,只是为了方便设定了客户端,服务端。此篇是搭载Unity使用的。.Net下也可以

【c#编程技术总结】Socket通信 Udp_ipad

【c#编程技术总结】Socket通信 Udp_客户端_02

public class UdpManager : MonoBehaviour
{
public Button server;
public Button client;

private Thread clientThread;
private Thread serverThread;

private Socket clientSocket;
private Socket serverSocket;

// 采用socket类,使用最基本的同步方法
void Start()
{
server.onClick.AddListener(StartServer);
client.onClick.AddListener(StartClient);
}

private void StartClient()
{
IPEndPoint ip = new IPEndPoint(IPAddress.Parse("192.168.10.99"), 7000);
clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
clientSocket.Bind(ip);
Debug.Log("启动客户端");
clientThread = new Thread(ClientThread);
clientThread.Start();

}
public void ClientThread( )
{
IPEndPoint ip = new IPEndPoint(IPAddress.Parse("192.168.10.99"), 7001);
try
{
while (true)
{
Thread.Sleep(100);

string welcome = "我是客户端";
Debug.Log("广播消息");
var data = Encoding.UTF8.GetBytes(welcome);
clientSocket.SendTo(data, data.Length, SocketFlags.None, ip);

IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
EndPoint Remote = sender;
var recdata = new byte[2048];
if (clientSocket.Available <= 0) continue;
int recv = clientSocket.ReceiveFrom(recdata, ref Remote);
Debug.Log(Encoding.UTF8.GetString(recdata, 0, recv)+ "from " + Remote.ToString());
}
}
catch (Exception e)
{
Debug.Log(e.Message);
}

clientSocket.Close();
}

private void StartServer()
{
IPEndPoint ip = new IPEndPoint(IPAddress.Parse("192.168.10.99"), 7001);
serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);

serverSocket.Bind(ip);


Debug.Log("启动服务器!");
serverThread = new Thread(ServerThread);
serverThread.Start();
}

public void ServerThread()
{
IPEndPoint sender = new IPEndPoint(IPAddress.Any, 7000);
EndPoint Remote = sender;

try
{
while (true)
{
if (serverSocket.Available <= 0) continue;
byte[] data = new byte[2048];
var recv = serverSocket.ReceiveFrom(data, ref Remote);
string recvStr = Encoding.UTF8.GetString(data, 0, recv);
Debug.Log(recvStr+ " from " + Remote.ToString());

//客户机连接成功后,发送信息
string welcome = "我是服务器: ";
serverSocket.SendTo(Encoding.UTF8.GetBytes(welcome), Remote);
}
}
catch (Exception e)
{
Debug.Log(e.Message);
}
}
private void OnDestroy()
{
if (clientThread!=null)
{
clientThread.Abort();
}
if (clientSocket!=null)
{
clientSocket.Close();
clientSocket = null;
}
if (serverThread!=null)
{
serverThread.Abort();
}
if (serverSocket!=null)
{
serverSocket.Close();
serverSocket = null;
}
}
}

欢迎加入Unity业内qq交流群:956187480