2021-07-25
作者:互联网
//服务器
Console.WriteLine(“服务器开始运行了…\n”);
Socket m_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//tcp协议
//bind绑定一个端口 any是接受任意段的ip
IPEndPoint ipEnd = new IPEndPoint(IPAddress.Any, 2019);
m_socket.Bind(ipEnd);//绑定端口
//listen 端口的接听
m_socket.Listen(10);//最多只能10个等待队列 就像是排队只能排10个人
Console.WriteLine(“等待一个接入…”);
Socket client_socket = m_socket.Accept();//如果有新的客户端链接这里,创建一个新的socket去链接
IPEndPoint ipEndClient = (IPEndPoint)client_socket.RemoteEndPoint;//获取客户端的链接信息
Console.WriteLine("链接的客户端的地址:{0},端口:{1}",ipEndClient.Address,ipEndClient.Port);//输出链接的ip地址 端口
//send 给客户端发送一个包 是字节形式的发送
byte[] sendBuf = new byte[1024];
string msg = "welcome!";
//
sendBuf = Encoding.Unicode.GetBytes(msg);//将msg(string)转换为byte因为数据流传输的数据是byte,并存储到sendBuf
client_socket.Send(sendBuf,sendBuf.Length,socketFlags:SocketFlags.None);
//receive 收到客户端的包时候要解析一下
byte[] recvBuf = new byte[1024];
int reclen = client_socket.Receive(recvBuf);//获取这个数据包的长度
string recvMsg = Encoding.Unicode.GetString(sendBuf, 0, reclen);//将接受到的byte类型的数据转换为string
Console.WriteLine("收到的信息是:{0}",recvMsg);
Console.WriteLine("断开链接{0}",ipEndClient.Address);
//最后需要关闭
client_socket.Close();
m_socket.Close();
Console.ReadKey();
标签:25,sendBuf,Console,socket,client,2021,WriteLine,byte,07 来源: https://blog.csdn.net/m0_52021450/article/details/119077931