欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C#使用Socket实现服务器与多个客户端通信(简单的聊天系统)

程序员文章站 2023-11-19 14:15:13
扩展:由于server端是存储了所有server与client的连接对象,因此我们是可以基于此demo的基础上实现聊天系统:* 每当一个与用户发言时,是由server接收到的某个用户的发言信息的,此时...

扩展:
由于server端是存储了所有server与client的连接对象,因此我们是可以基于此demo的基础上实现聊天系统:

* 每当一个与用户发言时,是由server接收到的某个用户的发言信息的,此时服务器端可以通过循环发送该用户发送的信息给每个已经连接连接的用户(排除发送者)。

server端代码:

class program
{
  //创建一个和客户端通信的套接字
  static socket socketwatch = null;
  //定义一个集合,存储客户端信息
  static dictionary<string, socket> clientconnectionitems = new dictionary<string, socket> { };
 
  static void main(string[] args)
  {
    //端口号(用来监听的)
    int port = 6000;
 
    //string host = "127.0.0.1";
    //ipaddress ip = ipaddress.parse(host);
    ipaddress ip = ipaddress.any;
 
    //将ip地址和端口号绑定到网络节点point上 
    ipendpoint ipe = new ipendpoint(ip, port);
 
    //定义一个套接字用于监听客户端发来的消息,包含三个参数(ip4寻址协议,流式连接,tcp协议) 
    socketwatch = new socket(addressfamily.internetwork, sockettype.stream, protocoltype.tcp);
    //监听绑定的网络节点 
    socketwatch.bind(ipe);
    //将套接字的监听队列长度限制为20 
    socketwatch.listen(20);
 
 
    //负责监听客户端的线程:创建一个监听线程 
    thread threadwatch = new thread(watchconnecting);
    //将窗体线程设置为与后台同步,随着主线程结束而结束 
    threadwatch.isbackground = true;
    //启动线程   
    threadwatch.start();
 
    console.writeline("开启监听......");
    console.writeline("点击输入任意数据回车退出程序......");
    console.readkey();
 
    socketwatch.close();
 
    //socket serversocket = null;
 
    //int i=1;
    //while (true)
    //{
    //  //receive message
    //  serversocket = socketwatch.accept();
    //  console.writeline("连接已经建立!");
    //  string recstr = "";
    //  byte[] recbyte = new byte[4096];
    //  int bytes = serversocket.receive(recbyte, recbyte.length, 0);
    //  //recstr += encoding.ascii.getstring(recbyte, 0, bytes);
    //  recstr += encoding.getencoding("utf-8").getstring(recbyte, 0, bytes);
 
    //  //send message
    //  console.writeline(recstr);
 
    //  console.write("请输入内容:");
    //  string sendstr = console.readline();
 
    //  //byte[] sendbyte = encoding.ascii.getbytes(sendstr);
    //  byte[] sendbyte = encoding.getencoding("utf-8").getbytes(sendstr);
 
    //  //thread.sleep(4000);
 
    //  serversocket.send(sendbyte, sendbyte.length, 0);
    //  serversocket.close();
    //  if (i >= 100)
    //  {
    //    break;
    //  }
    //  i++;
    //}
      
    //ssocket.close();
    //console.writeline("连接关闭!");
 
 
    //console.readline();
  }
 
  //监听客户端发来的请求 
  static void watchconnecting()
  {
    socket connection = null;
 
    //持续不断监听客户端发来的请求   
    while (true)
    {
      try
      {
        connection = socketwatch.accept();
      }
      catch (exception ex)
      {
        //提示套接字监听异常   
        console.writeline(ex.message);
        break;
      }
 
      //客户端网络结点号 
      string remoteendpoint = connection.remoteendpoint.tostring();
      //添加客户端信息 
      clientconnectionitems.add(remoteendpoint, connection);
      //显示与客户端连接情况
      console.writeline("\r\n[客户端\"" + remoteendpoint + "\"建立连接成功! 客户端数量:" + clientconnectionitems .count+ "]");
 
      //获取客户端的ip和端口号 
      ipaddress clientip = (connection.remoteendpoint as ipendpoint).address;
      int clientport = (connection.remoteendpoint as ipendpoint).port;
 
      //让客户显示"连接成功的"的信息 
      string sendmsg = "[" + "本地ip:" + clientip + " 本地端口:" + clientport.tostring() + " 连接服务端成功!]";
      byte[] arrsendmsg = encoding.utf8.getbytes(sendmsg);
      connection.send(arrsendmsg);
 
      //创建一个通信线程   
      thread thread = new thread(recv);
      //设置为后台线程,随着主线程退出而退出 
      thread.isbackground = true;
      //启动线程   
      thread.start(connection);
    }
  }
 
  /// <summary>
  /// 接收客户端发来的信息,客户端套接字对象
  /// </summary>
  /// <param name="socketclientpara"></param>  
  static void recv(object socketclientpara)
  {
    socket socketserver = socketclientpara as socket;
 
    while (true)
    {
      //创建一个内存缓冲区,其大小为1024*1024字节 即1m   
      byte[] arrserverrecmsg = new byte[1024 * 1024];
      //将接收到的信息存入到内存缓冲区,并返回其字节数组的长度  
      try
      {
        int length = socketserver.receive(arrserverrecmsg);
 
        //将机器接受到的字节数组转换为人可以读懂的字符串   
        string strsrecmsg = encoding.utf8.getstring(arrserverrecmsg, 0, length);
 
        //将发送的字符串信息附加到文本框txtmsg上   
        console.writeline("\r\n[客户端:" + socketserver.remoteendpoint + " 时间:" + datetime.now.tostring("yyyy-mm-dd hh:mm:ss:fff")+ "]\r\n" + strsrecmsg);
 
        //thread.sleep(3000);
        //socketserver.send(encoding.utf8.getbytes("[" + socketserver.remoteendpoint + "]:"+strsrecmsg));
        //发送客户端数据
        if (clientconnectionitems.count > 0)
        {
          foreach (var sockettemp in clientconnectionitems)
          {
            sockettemp.value.send(encoding.utf8.getbytes("[" + socketserver.remoteendpoint + "]:" + strsrecmsg));
          }
        }
      }
      catch (exception)
      {
        clientconnectionitems.remove(socketserver.remoteendpoint.tostring());
        //提示套接字监听异常 
        console.writeline("\r\n[客户端\"" + socketserver.remoteendpoint + "\"已经中断连接! 客户端数量:" + clientconnectionitems.count+"]");
        //关闭之前accept出来的和客户端进行通信的套接字 
        socketserver.close();
        break;
      }
    }
  }
}

client端代码:

class program
{
  //创建1个客户端套接字和1个负责监听服务端请求的线程 
  static thread threadclient = null;
  static socket socketclient = null;
 
  static void main(string[] args)
  {
    try
    {
      int port = 6000;
      string host = "127.0.0.1";//服务器端ip地址
 
      ipaddress ip = ipaddress.parse(host);
      ipendpoint ipe = new ipendpoint(ip, port);
 
      //定义一个套接字监听 
      socketclient = new socket(addressfamily.internetwork, sockettype.stream, protocoltype.tcp);
 
      try
      {
        //客户端套接字连接到网络节点上,用的是connect 
        socketclient.connect(ipe);
      }
      catch (exception)
      {
        console.writeline("连接失败!\r\n");
        console.readline();
        return;
      }
 
      threadclient = new thread(recv);
      threadclient.isbackground = true;
      threadclient.start();
 
      thread.sleep(1000);
      console.writeline("请输入内容<按enter键发送>:\r\n");
      while(true)
      {
        string sendstr = console.readline();
        clientsendmsg(sendstr);
      }
 
      //int i = 1;
      //while (true)
      //{
      //  console.write("请输入内容:");
      //  string sendstr = console.readline();
 
      //  socket clientsocket = new socket(addressfamily.internetwork, sockettype.stream, protocoltype.tcp);
      //  clientsocket.connect(ipe);
      //  //send message
      //  //byte[] sendbytes = encoding.ascii.getbytes(sendstr);
      //  byte[] sendbytes = encoding.getencoding("utf-8").getbytes(sendstr);
 
      //  //thread.sleep(4000);
 
      //  clientsocket.send(sendbytes);
 
      //  //receive message
      //  string recstr = ""; 
      //  byte[] recbytes = new byte[4096];
      //  int bytes = clientsocket.receive(recbytes, recbytes.length, 0);
      //  //recstr += encoding.ascii.getstring(recbytes, 0, bytes);
      //  recstr += encoding.getencoding("utf-8").getstring(recbytes, 0, bytes);
      //  console.writeline(recstr);
 
      //  clientsocket.close();
      //  if (i >= 100)
      //  {
      //    break;
      //  }
      //  i++;
      //}
        
      //console.readline();
      //return;
 
      //string result = string.empty;
 
    }
    catch (exception ex) 
    {
      console.writeline(ex.message);
      console.readline();
    }
  }
 
  //接收服务端发来信息的方法  
  public static void recv()
  {
      int x = 0;
    //持续监听服务端发来的消息 
    while (true)
    {
      try
      {
        //定义一个1m的内存缓冲区,用于临时性存储接收到的消息 
        byte[] arrrecvmsg = new byte[1024 * 1024];
 
        //将客户端套接字接收到的数据存入内存缓冲区,并获取长度 
        int length = socketclient.receive(arrrecvmsg);
 
        //将套接字获取到的字符数组转换为人可以看懂的字符串 
        string strrevmsg = encoding.utf8.getstring(arrrecvmsg, 0, length);
        if (x == 1)
        {
          console.writeline("\r\n服务器:" + datetime.now.tostring("yyyy-mm-dd hh:mm:ss:fff") + "\r\n" + strrevmsg+"\r\n");
            
        }
        else
        {
          console.writeline(strrevmsg + "\r\n");
          x = 1;
        }
      }
      catch (exception ex)
      {
        console.writeline("远程服务器已经中断连接!" + ex.message + "\r\n");
        break;
      }
    }
  }
 
  //发送字符信息到服务端的方法 
  public static void clientsendmsg(string sendmsg)
  {
    //将输入的内容字符串转换为机器可以识别的字节数组   
    byte[] arrclientsendmsg = encoding.utf8.getbytes(sendmsg);
    //调用客户端套接字发送字节数组   
    socketclient.send(arrclientsendmsg);
  }  
}

测试结果:

server端:

C#使用Socket实现服务器与多个客户端通信(简单的聊天系统)

client端:

C#使用Socket实现服务器与多个客户端通信(简单的聊天系统)

C#使用Socket实现服务器与多个客户端通信(简单的聊天系统)

C#使用Socket实现服务器与多个客户端通信(简单的聊天系统)

代码下载地址:c-socket_jb51.zip

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。