C#学习笔记-基于Socker通讯开发的TCP/IP服务器客户端

Socker服务器
服务器端程序的编写步骤:
第一步:调用socket()函数创建一个用于通信的套接字。

Socker  socketClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint ipe = new IPEndPoint(IPAddress.Parse(this.txtIpAdress.Text),int.Parse(this.txtIpPort.Text));


第二步:给已经创建的套接字绑定一个端口号,这一般通过设置网络套接口地址和调用bind()函数来实现。

socketClient.Connect(ipe);//绑定IPhe 端口号


第三步:调用listen()函数使套接字成为一个监听套接字。

//使用多线程监听
socketService.Listen(10);
Task.Run(new Action(() =>
{
    CheckListening();
}));

   第四步:调用accept()函数来接受客户端的连接,这是就可以和客户端通信了。 

   private void CheckListening()
   {
     while (true)
     {
               
       Socket socketClient = socketService.Accept();//Accept获取连接的客户端对象
       string client = socketClient.RemoteEndPoint.ToString();//获取Socker对象的信息
       AddLog(client+"连接服务器");
       UpdataOnLine(client,true);
       currentClientList.Add(client, socketClient);
       Task.Run(new Action(() =>
       {
          ReceiceMessage(socketClient);//接收客户端发送的消息
       }));
      }
    }

Accept()方法带有阻塞,只有当服务器连接的客户端,发生改变,后续的代码才会被继续执行
     
 第五步:处理客户端的连接请求。

        private void ReceiceMessage(Socket socketClient)
        {
            while (true)
            {
                byte[] buffer = new byte[1024 * 1024 * 10];
                int length = -1;
                string client = socketClient.RemoteEndPoint.ToString();
                try
                {
                    length = socketClient.Receive(buffer);
                }
                catch (Exception)
                {
                    AddLog(client + " 下线了");
                    UpdataOnLine(client, false);
                    currentClientList.Remove(client);
                    break;
                }
                if (length > 0)
                {
                    string receiveMsg = Encoding.ASCII.GetString(buffer,0,length);
                    AddLog(receiveMsg);
                }
                else
                {
                    AddLog(client + " 下线了");
                    UpdataOnLine(client, false);
                    currentClientList.Remove(client);
                    break;
                }
            }
            
        }


     第六步:终止连接     

    发送消息:通过Socker对象的send方法去发送消息,服务器这里的Socker对象是客户端,发送的消息位byte数组,不同类型数组解析的byte,客户端接收的解析对应类型(ASCII、UTF-8、Hex、File、Json等等)

        private void btnSend_Click(object sender, EventArgs e)
        {
            if (lst_OnLine.SelectedItems.Count > 0)
            {
                foreach(string item in lst_OnLine.SelectedItems)
                {
                    byte[] send = Encoding.ASCII.GetBytes(this.txtSendMsg.Text);
                    AddLog("发送了消息:"+this.txtSendMsg.Text);
                    currentClientList[item].Send(send);
                    this.txtSendMsg.Clear();
                }
            }
            else
            {
                MessageBox.Show("请选择链接的客户端", "选择客户端");
            }
        }

     byte数组: byte[] send = Encoding.ASCII.GetBytes(this.txtSendMsg.Text);

     开发中还可以给这个数组做一个标志位byte[0]的位置,创建一个新的数组发送  

            byte[] send = Encoding.ASCII.GetBytes(this.txtSendMsg.Text);
            byte[] sendMsg = new byte[send.Length + 1];
            Array.Copy(send, 0, sendMsg, 1, send.Length);
            sendMsg[0] = (byte)MessageType.ASCII;

 

Socker客户端

          客户端程序编写步骤:
          第一步:调用socket()函数创建一个用于通信的套接字。
          第二步:通过设置套接字地址结构,说明客户端与之通信的服务器的IP地址和端口号。
          第三步:调用connect()函数来建立与服务器的连接。
          第四步:调用读写函数发送或者接收数据。
          第五步:终止连接。

           

private Socket  socketClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint ipe = new IPEndPoint(IPAddress.Parse(this.txtIpAdress.Text),int.Parse(this.txtIpPort.Text));
try
 {
    socketClient.Connect(ipe);//绑定IPhe 端口号
 }
catch (Exception ex)
 {
    AddLog("服务器连接失败"+ex.Message);
 }          
        
 Task.Run(new Action(() =>
 {
    ReceiceMessage(socketClient);
 }));

 接收消息的方法

        private void ReceiceMessage(Socket socketClient)
        {
            while (true)
            {
                byte[] buffer = new byte[1024 * 1024 * 10];//创建一个BUFFER缓冲区 
                int length = -1;
                string client = socketClient.RemoteEndPoint.ToString();
                try
                {
                    length = socketClient.Receive(buffer);
                }
                catch (Exception)
                {
                    AddLog(client + " 服务器断开");                  
                    break;
                }
                if (length > 0)
                {
                    string receiveMsg = Encoding.ASCII.GetString(buffer,0,length);
                    AddLog(receiveMsg);
                }
                else
                {
                    AddLog(client + " 服务器断开");                
                    break;
                }
            }
            
        }

发送消息

 byte[] send = Encoding.ASCII.GetBytes(this.txtSendMsg.Text);
 AddLog("发送了消息:" + this.txtSendMsg.Text);
 socketClient.Send(send);
 this.txtSendMsg.Clear();

PS:Socker客户端只需要创建一个Socker对象,用这个对象发送和接收消息即可,Socker服务器需要根据客户端去捕获连接对象(Socker)  ,让后通过这个对象去发送和接收消息。本博客的Demo链接:https://download.csdn.net/download/qq_39157152/19683415?spm=1001.2014.3001.5503

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值