一、客户端:
1:Socket创建和连接
socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socket.Connect("127.0.0.1", 8888);
2:客户端发送内容(转为字节流)
string sendStr = inputField.text;
byte[] sendBytes = System.Text.Encoding.Default.GetBytes(sendStr);
socket.Send(sendBytes);
其中Send函数是
public int Send(byte[] buffer, int offset, int size, SocketFlags socketFlags);
Offset是要发送的数据在字节数组中的起始位置
size是要发送的数据的字节数
3:客户端接收内容(转为String)
byte[] readBuff = new byte[1024];
int count = socket.Receive(readBuff);//Receive函数返回int值
string recvStr = System.Text.Encoding.Default.GetString(readBuff, 0, count);
text.text = recvStr;
socket.Close();
其中Receive函数是
public int Receive(byte[] buffer, int offset, int size, SocketFlags socketFlags);
GetString函数是
public virtual string GetString(byte[] bytes, int index, int count);
index是解码位置
count是解码字节数(来自Receive返回)
二、服务端
1:Socket连接和绑定服务器
static Socket listenfd;
listenfd = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPAddress ipAdr = IPAddress.Parse("127.0.0.1");
IPEndPoint ipEp = new IPEndPoint(ipAdr, 8888);
listenfd.Bind(ipEp);
listenfd.Listen(0);
Console.WriteLine("[服务器]启动成功");
2:建立服务端和客户端连接,接收来自客户端的消息
while (true)
{
Socket clientfd = listenfd.Accept();
Console.WriteLine ("[服务器]Accept");
byte[] readBuff = new byte[1024];
int count = connfd.Receive (readBuff);
string readStr = System.Text.Encoding.Default.GetString (readBuff, 0, count);
Console.WriteLine ("[服务器接收]" + readStr);
}
Socket clientfd = listenfd.Accept(); 建立客户端和服务端的Socket
3:将服务端接收到的消息发送给客户端
byte[] sendBytes = System.Text.Encoding.Default.GetBytes(readStr);
connfd.Send(sendBytes);