一、前言
接下来是客户端的设计和使用,因为和服务端是两个类,可以封装在一个库内或者单独封装,服务器端可以接收多客户端。
二、客户端
1.变量定义,与服务器端相同的数据结构
/*1.创建发送接收信息格式,各个参数以#分割*/
public struct Message
{
public int msg1;
public int msg2;
public string msg3;
public Message(int msg1, int msg2, string msg3)
{
this.msg1 = msg1;
this.msg2 = msg2;
this.msg3 = msg3;
}
}
public bool Status;//在线状态
public IPAddress Addr = IPAddress.Parse("127.0.0.1");
public int Port = 0;
public delegate void RecvMsg(Message msg);
public Socket socket { get; private set; }
public RecvMsg recvMsg { get; set; }
2.构造函数,在实例化时传入参数和回调函数。
/*2.构造传参,直接在实例化时写入ip port和callback*/
public Client(IPAddress addr,int port, RecvMsg _recvMsg)
{
Addr = addr;
Port = port;
recvMsg = _recvMsg;
}
3.创建连接,连接成功后直接开始创建线程并接收数据给回调函数
public bool NewConnection()
{
try
{
if(socket != null) return true;
socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socket.Connect(new IPEndPoint(Addr, Port));
Status = true;
/*链接成功,开始循环接收信息*/
new Thread(() => {
Socket socket2 = socket;
while (Status)
{
if (!Status) break;
recvMsg(Bytes2Msg(socket2));
//Thread.Sleep(10);/*10ms延时*/
}
}).Start();
return true;
}
catch (Exception ex)
{
Status = false;
socket?.Close();
socket = null;
return false;
}
}
4.断开连接,并恢复状态
public bool DisConnection()
{
if(Status)
{
socket?.Close();
socket = null;
Status = false;
}
return true;
}
5.发送数据,使用#作为分割符,实际是结构体转字符串发送数据
public bool SendMsg(Message msg)
{
try
{
if (!Status || socket == null) return false;
string data = $"{msg.msg1}#{msg.msg2}#{msg.msg3}";
byte[] buffer = Encoding.ASCII.GetBytes(data);
int len = socket.Send(buffer);
if(len == buffer.Length)
return true;
return false;
}
catch (Exception ex)
{
return false;
}
}
6.其他函数,接收的数据转成结构体并在接收线程调用。
//从字节转成结构 以# 作为分隔符,utf-8
Message Bytes2Msg(Socket socket)
{
int len = socket.Available;
if(len > 0 )
{
byte[] buf = new byte[len];
if(socket.Receive(buf)>0)
{
Message message = new Message();
string[] buffer = Encoding.ASCII.GetString(buf).Split('#') ;
if (buffer.Length == 3)
{
message.msg1 = int.Parse(buffer[0]) ;
message.msg2 = int.Parse(buffer[1]) ;
message.msg3 = buffer[2] ;
return message;
}
}
}
return default;
}
三、声明
代码链接:https://download.csdn.net/download/qq_35355765/89301837