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

C#利用服务器实现客户端之间通信

程序员文章站 2023-11-17 13:33:28
先来讲述下我自己对于整个socket通信过程的理解,毕竟初学,说错见谅,知道错了会改正~  首先在服务端新建一个serversocket,对其进行初始化(一...

先来讲述下我自己对于整个socket通信过程的理解,毕竟初学,说错见谅,知道错了会改正~ 

首先在服务端新建一个serversocket,对其进行初始化(一般包含addressfamily:ip地址类型,sockettype:socket传输数据方式,prototype:传输协议); 

接着我们要设置server端要绑定的ip:port;然后开始监听,并设置最多同时监听多少个client.

这时,服务端就在等待状态,直到某一个client连接到这个ip:port上,这时serversocket.accept()工作,获得这个连接。(此时的连接是有地址信息的哦!记得保存) 

获得连接之后,server就可以和这个client进行通信了,当加入第二个client(我们称其为clientb)时,server接收到clientb的消息,可以将这个消息转发给前一个client(我们称其为clienta),当受到clienta的消息,也可以转发给clientb。这样就实现了clients之间的通信了。(重点在保存连接信息!!)

那么现在贴上代码讲解:

server端代码 

namespace socketserver
{
  class program
  {
    private static byte[] result = new byte[1024];
   
    static socket serversocket;
    private static string client;
    private static socket clientsocket;
    //我这里存了两个client,因为自己电脑开了两个client,不会有多的
    //理论上应该开一个socket[]来保存信息,最好用一个二元组将client的信息和连接绑定起来
    //这样就可以实现断开连接后下次登陆还是可以识别是这个client
    private static socket clientsocketa=null;
    private static socket clientsocketb=null;
    
    static void main(string[] args)
    {
      program.setport(8885);
    }
    private static void setport(int port)
    {
      ipaddress ip = ipaddress.parse("127.0.0.1");//set ip
      serversocket = new socket(addressfamily.internetwork,
        sockettype.stream, protocoltype.tcp);//initialize
      serversocket.bind(new ipendpoint(ip, port));//bind
      serversocket.listen(10);
      //进入监听状态
      console.writeline("监听{0}成功", serversocket.localendpoint.tostring());
      //开启一个线程来监听客户端连接
      thread mythread = new thread(listenclientconnect);
      mythread.start();
      console.readline();

    }
    /// <summary>
    /// 监听客户端连接
    /// </summary>
    private static void listenclientconnect()
    {
      while (true)
      {
        //client连接上后 得到这个连接
        clientsocket = serversocket.accept();

        //这里我因为只有两个client,所以就简单写了
        if (clientsocketa == null)
        {
          clientsocketa = clientsocket;
        }
        else if (clientsocketb == null)
        {
          clientsocketb = clientsocket;
        }
        else
        {
          //当其中一个断开了,又重新连接时,需要再次保存连接
          if (clientsocketb.isbound)
          {
            clientsocketa = clientsocketb;
            clientsocketb = clientsocket;
          }
          else
          {
            clientsocketb = clientsocketa;
            clientsocketa = clientsocket;
          }
          
        }
        clientsocket.send(encoding.ascii.getbytes("say hello"));
        //开个线程接收client信息
        thread receivedthread = new thread(receivemessage);
        receivedthread.start(clientsocket);

      }
    }
   
    private static void receivemessage(object clientsocket)
    {
      socket myclientsocket = (socket) clientsocket;
      
      while (true)
      {
        try
        {
          int revceivenumber = myclientsocket.receive(result);
          //console.writeline("接受客户端{0}消息{1}", myclientsocket.remoteendpoint.tostring()
          //  , encoding.ascii.getstring(result, 0, revceivenumber));
          console.writeline(encoding.ascii.getstring(result, 0, revceivenumber));
          if (myclientsocket == clientsocketa)
          {
            console.writeline("receive from a");
            if (clientsocketb!=null&&clientsocketb.isbound)
            {
              console.writeline("a is bound");
              clientsocketb.send(result, 0, revceivenumber, socketflags.none);
            }
            else
            {
              myclientsocket.send(encoding.ascii.getbytes("the people is not online! send failed!"));
              console.writeline("对方不在线上,发送失败!");
            }
          }
          else
          {
            console.writeline("receive from b");
            if (clientsocketa != null && clientsocketa.isbound)
            {
              console.writeline("a is bound");
              clientsocketa.send(result, 0, revceivenumber, socketflags.none);
            }  
            else
            {
              myclientsocket.send(encoding.ascii.getbytes("the people is not online! send failed!"));
              console.writeline("对方不在线上,发送失败!");
            }

          }
          
        }
        catch(exception ex)
        {
          console.writeline(ex.message);
          myclientsocket.shutdown(socketshutdown.both);
          myclientsocket.close();
          break;

        }
      }

    }
  }
}

client端代码(因为都差不多 就只贴一个了) 

namespace socketclient
{
  class program
  {
    private static byte[] result = new byte[1024];
    private static socket clientsocket;
    private static void listenserver()
    {
      while (true)
      {
        result = new byte[1024];
        int receivelength = clientsocket.receive(result);
        
        console.writeline("{0}", encoding.ascii.getstring(result, 0, receivelength));
      }
      
    }
    static void main(string[] args)
    {

      ipaddress ip = ipaddress.parse("127.0.0.1");
      clientsocket = new socket(addressfamily.internetwork, sockettype.stream, protocoltype.tcp);
      try
      {
        clientsocket.connect(ip, 8885);
        console.writeline("连接成功!");

      }
      catch (exception e)
      {
        console.writeline("连接失败!");
        return;
      }
      thread threadread = new thread(listenserver);
      threadread.start();
     

      while(true)
      {
        try
        {
          thread.sleep(1000);
          string sendmessage = console.readline();
          clientsocket.send(encoding.ascii.getbytes("sylvia:"+sendmessage));
          
        }
        catch (exception ex)
        {
          clientsocket.shutdown(socketshutdown.both);
          clientsocket.close();
          break;
        }

      }
      console.writeline("发送完毕 按回车退出");
      console.readkey();
    }
  }
}

写的时候要特别注意一下send信息的时候,注意byte[]的传输大小,很容易变成byte[]数组的大小而不是内容的大小。 

这个大家就自己尝试吧。

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