unity socket通信服务器端程序<<unity3D 网络游戏实战>>
using System;
using System.Net;
using System.Net.Sockets;
class MainClass
{
public static void Main(string[] args)
{
Console.WriteLine("Hello World!");
//创建一个套接字,三个参数分别代表地址族,套接字类型和协议
Socket listenfd = new Socket(AddressFamily.InterNetwork,SocketType.Stream, ProtocolType.Tcp);
//根据IP地址创建IPAddress对象
IPAddress ipAdr = IPAddress.Parse("127.0.0.1");
//用IPAddress指定的地址和端口初始化;
IPEndPoint ipEp = new IPEndPoint(ipAdr, 1234);
//给套接字绑定IP和端口
listenfd.Bind(ipEp);
//开始监听,等待客户端连接;
listenfd.Listen(0);
Console.WriteLine("[服务器]启动成功");
while (true)
{
//Accept
Socket connfd = listenfd.Accept();
Console.WriteLine("[服务器]Accept");
//Recv
byte[] readBuff = new byte[1024];
int count = connfd.Receive(readBuff);
string str = System.Text.Encoding.UTF8.GetString(readBuff, 0, count);
Console.WriteLine("[服务器接收]" + str);
//Send
byte[] bytes = System.Text.Encoding.Default.GetBytes("serv echo " + str);
connfd.Send(bytes);
}
}
}
服务端要处理多个客户端消息,它需要一个数组来维护所有客户端的连接,每个客户端都有自己的Socket和缓冲区,在服务端添加Conn类。
using System;
using System.Net;
using System.Net.Sockets;
using System.Collections;
using System.Collections.Generic;
public class Conn
{
//常量
public const int BUFFER_SIZE = 1024;
//Socket
public Socket socket;
//是否使用
public bool isUse = false;
//Buff
public byte[] readBuff = new byte[BUFFER_SIZE];
public int buffCount = 0;
//构造函数
public Conn()
{
readBuff = new byte[BUFFER_SIZE];
}
//初始化
public void Init(Socket socket)
{
this.socket = socket;
isUse = true;
buffCount = 0;
}
//缓冲区剩余的字节数
public int BuffRemain()
{
return BUFFER_SIZE - buffCount;
}
//获取客户端地址
public string GetAdress()
{
if (!isUse)
return "无法获取地址";
return socket.RemoteEndPoint.ToString();
}
//关闭
public void Close()
{
if (!isUse)
return;
Console.WriteLine("[断开链接]" + GetAdress());
socket.Close();
isUse = false;
}
}