当前位置: 移动技术网 > IT编程>开发语言>.net > C#利用服务器实现客户端之间通信

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

2017年12月12日  | 移动技术网IT编程  | 我要评论

公积金贷款额度,环保材料 英语,传奇行会名

先来讲述下我自己对于整个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[]数组的大小而不是内容的大小。 

这个大家就自己尝试吧。

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

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网