前言
作者每次使用网络通信时,都需要重新编写各种发送接收函数,有时候忘记函数又不得不百度一下,所以想写一个封装的dll来(只是一个基础通信库,使用时可以通过单例模式等自行封装)
一、创建项目
创建新项目-->类库(net.framework)-->修改类库名称和存储地址(如有不懂,可以看控件Button的创建过程).
修改类名并创建新类
二、Server服务器端
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;
}
}
2.变量
public bool Status;//连接状态
Socket socket { get ; set; }
IPAddress Host { get; set; }
public int Port;
public delegate void RecvMsg(Message msg);
RecvMsg recvMsg { get; set; }//接收函数
Dictionary<string,Socket> clients = new Dictionary<string,Socket>();/*客户端键值对*/
public struct SubClint
{
public IPAddress c1;
public IPAddress c2;
public IPAddress c3;
}
public SubClint subClint = new SubClint();//客户端地址,根据需要添加
3.构造函数
public Server(IPAddress host, int port,RecvMsg _recvMsg)//传递地址和回调函数
{
Host = host;
Port = port;
recvMsg = _recvMsg;
}
4.连接,接收消息
//连接并接收信息
public bool NewClient()
{
try
{
socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socket.Bind(new IPEndPoint(Host, Port));
socket.Listen(3);
Status = true;
new Thread(() => {
while (Status)
{
Socket socket2 = socket.Accept();
string dirId = socket2.RemoteEndPoint.ToString().Split(':')[0];
if(!clients.ContainsKey(dirId))
clients.Add(dirId, socket2);
else
clients[dirId] = socket2;
while (Status)
{
int len = socket2.Available;
if (len > 0)
{
Message msg = new Message();
byte[] buf = new byte[len];
socket2.Receive(buf);
string strId = socket2.RemoteEndPoint.ToString().Split(':')[0];
if(strId == subClint.c1.ToString())
{
string[] str = Encoding.ASCII.GetString(buf).Split('#');
if(str.Length == 3)
{
msg.msg1 = int.Parse(str[0]);
msg.msg2 = int.Parse(str[1]);
msg.msg3 = str[2];
recvMsg(msg);
}
}
}
}
}
}).Start();
return true;
}
catch (Exception ex)
{
Status = false;
return false;
}
}
5.断开连接
public bool DisClient()
{
if (Status)
{
socket?.Close();
}
Status = false;
return true;
}
6.发送信息
public bool SendData(Message msg)
{
Dictionary<string ,Socket>.KeyCollection keys = clients.Keys;
foreach (string key in keys)
{
if(subClint.c1.ToString() == key && (Send(msg,key)))
{
return true;
}
}
return false;
}
bool Send(Message str, string id)
{
if(!clients.ContainsKey(id))
{
return false;
}
Socket socket = clients[id];
if (socket == null) return false;
try
{
string str1 = $"{str.msg1}#{str.msg2}#{str.msg3}";
byte[] buf = Encoding.ASCII.GetBytes(str1);
socket.Send(buf);
return true;
}
catch (Exception ex)
{
clients.Remove(id);
return false;
}
}
三、声明
代码链接:https://download.csdn.net/download/qq_35355765/89301634