• C#套接字(服务器)不会收取任何景致

  • 本文关于 c#,套接口sockets,receiving
  • CodeGo.net > C#套接字(服务器)不会收取任何景致
  •  

    C#套接字(服务器)不会收取任何景致



    c# 套接口sockets receiving
    我试图让在C#中一种先进的聊天。我没有新的节目,但它是接近我的优先个TCP聊天。 的问题是,我Socket(服务器)看起来不收取任何景致。在我void ReceiveDataListener这是一个BackgroundWorker,我加Console.WriteLine();检查它锁定,只显示优先个Console.WriteLine("Receive Data Listener 0")。我知道这是正常的,Socket.Receive()锁定直到景致收到,但它似乎停留锁定 CodeGo.net,即使我送景致。 我也想补充一点,我的事件onClientConnectonClientDisconnect被调用细,所以我知道客户端端连接的罚款。 这里是我的服务器类的代码:
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Net;
    using System.Net.Sockets;
    using System.ComponentModel;
    using System.Threading;
    namespace JAChat.Library
    {
     class SocketServer
     {
      private Socket socket;
      private BackgroundWorker bwSocketConnectListener;
      private BackgroundWorker bwCheckIfConnected;
      private BackgroundWorker bwReceiveDataListener;
      private List<ClientManager> clientsList;
      #region Constructor
      public SocketServer(int port)
      {
       clientsList = new List<ClientManager>();
       socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
       socket.Bind(new IPEndPoint(IPAddress.Any, port));
       socket.Listen(100);
       bwSocketConnectListener = new BackgroundWorker();
       bwSocketConnectListener.DoWork += new DoWorkEventHandler(ListenSocketConnection);
       bwSocketConnectListener.RunWorkerAsync();
       bwCheckIfConnected = new BackgroundWorker();
       bwCheckIfConnected.DoWork += CheckIfClientStillConnectedThread;
       bwCheckIfConnected.RunWorkerAsync();
       bwReceiveDataListener = new BackgroundWorker();
       bwReceiveDataListener.DoWork += ReceiveDataListener;
       bwReceiveDataListener.RunWorkerAsync();
      }
      #endregion
      #region Getter
      public List<ClientManager> connectedClients
      {
       get
       {
        return clientsList;
       }
      }
      #endregion
      #region Public Methods
      /// <summary>
      /// Parse and send the command object to targets
      /// </summary>
      public void sendCommand(Command cmd)
      {
       BackgroundWorker test = new BackgroundWorker();
       test.DoWork += delegate {
        foreach(ClientManager cManager in clientsList){
         cManager.sendCommand(cmd);
        }
       };
       test.RunWorkerAsync();
      }
      /// <summary>
      /// Disconnect and close the socket
      /// </summary>
      public void Disconnect()
      {
       socket.Disconnect(false);
       socket.Close();
       socket = null; //Stop some background worker
      }
      #endregion
      #region Private Methods
      private void ListenSocketConnection(object sender, DoWorkEventArgs e)
      {
       while (socket != null)
       {
        //Get and WAIT for new connection
        ClientManager newClientManager = new ClientManager(socket.Accept());
        clientsList.Add(newClientManager);
        onClientConnect.Invoke(newClientManager);
       }
      }
      private void CheckIfClientStillConnectedThread(object sender, DoWorkEventArgs e){
       while(socket != null){
        for(int i=0;i<clientsList.Count;i++){
         if(clientsList[i].socket.Poll(10,SelectMode.SelectRead) && clientsList[i].socket.Available==0){
          clientsList[i].socket.Close();
          onClientDisconnect.Invoke(clientsList[i]);
          clientsList.Remove(clientsList[i]);
          i--;      
         }
        }
        Thread.Sleep(5);
       }
      }
      private void ReceiveDataListener(object sender, DoWorkEventArgs e){
       while (socket != null){
        Console.WriteLine("Receive Data Listener 0");
        //Read the command's Type.
        byte[] buffer = new byte[4];
        int readBytes = this.socket.Receive(buffer, 0, 4, SocketFlags.None);
        Console.WriteLine("Receive Data Listener 1");
        if (readBytes == 0)
         break;
        Console.WriteLine("Receive Data Listener 2");
        CommandType cmdType = (CommandType)(BitConverter.ToInt32(buffer, 0));
        Console.WriteLine("Receive Data Listener 3");
        //Read the sender IP size.
        buffer = new byte[4];
        readBytes = this.socket.Receive(buffer, 0, 4, SocketFlags.None);
        if (readBytes == 0)
         break;
        int senderIPSize = BitConverter.ToInt32(buffer, 0);
        //Read the sender IP.
        buffer = new byte[senderIPSize];
        readBytes = this.socket.Receive(buffer, 0, senderIPSize, SocketFlags.None);
        if (readBytes == 0)
         break;
        IPAddress cmdSenderIP = IPAddress.Parse(System.Text.Encoding.ASCII.GetString(buffer));
        //Read the sender name size.
        buffer = new byte[4];
        readBytes = this.socket.Receive(buffer, 0, 4, SocketFlags.None);
        if (readBytes == 0)
         break;
        int senderNameSize = BitConverter.ToInt32(buffer, 0);
        //Read the sender name.
        buffer = new byte[senderNameSize];
        readBytes = this.socket.Receive(buffer, 0, senderNameSize, SocketFlags.None);
        if (readBytes == 0)
         break;
        string cmdSenderName = System.Text.Encoding.Unicode.GetString(buffer);
        //Read target IP size.
        string cmdTarget = "";
        buffer = new byte[4];
        readBytes = this.socket.Receive(buffer, 0, 4, SocketFlags.None);
        if (readBytes == 0)
         break;
        int targetIPSize = BitConverter.ToInt32(buffer, 0);
        //Read the command's target.
        buffer = new byte[targetIPSize];
        readBytes = this.socket.Receive(buffer, 0, targetIPSize, SocketFlags.None);
        if (readBytes == 0)
         break;
        cmdTarget = System.Text.Encoding.ASCII.GetString(buffer);
        //Read the command's MetaData size.
        string cmdMetaData = "";
        buffer = new byte[4];
        readBytes = this.socket.Receive(buffer, 0, 4, SocketFlags.None);
        if (readBytes == 0)
         break;
        int metaDataSize = BitConverter.ToInt32(buffer, 0);
        //Read the command's Meta data.
        buffer = new byte[metaDataSize];
        readBytes = this.socket.Receive(buffer, 0, metaDataSize, SocketFlags.None);
        if (readBytes == 0)
         break;
        cmdMetaData = System.Text.Encoding.Unicode.GetString(buffer);
        //Create the command object
        Command cmd = new Command(cmdType, cmdSenderIP, cmdSenderName, IPAddress.Parse(cmdTarget), cmdMetaData);
        this.onCommandReceived(cmd);
       }
       Console.WriteLine("Receive data listener closed");
      }
      #endregion
      #region Events
      public delegate void OnClientConnectEventHandler(ClientManager client);
      /// <summary>
      /// Events invoked when a client connect to the server
      /// </summary>
      public event OnClientConnectEventHandler onClientConnect = delegate { };
      public delegate void OnClientDisconnectEventHandler(ClientManager client);
      /// <summary>
      /// Events invoked when a client disconnect from the server
      /// </summary>
      public event OnClientDisconnectEventHandler onClientDisconnect = delegate { };
      public delegate void OnCommandReceivedEventHandler(Command cmd);
      /// <summary>
      /// Events invoked when a command has been sent to the server
      /// </summary>
      public event OnCommandReceivedEventHandler onCommandReceived = delegate { };
      #endregion
     }
    }
    
    这里是通过发送数据,建立测试服务器的代码:
    clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
      clientSocket.Connect("localhost", 2000);
      networkStream = new NetworkStream(clientSocket);
    
     //CommandType
     byte[] buffer = new byte[4];
     buffer = BitConverter.GetBytes(1);
     this.networkStream.Write(buffer, 0, 4);
     this.networkStream.Flush();
     //Sender IP + Size
     byte[] senderIPBuffer = Encoding.ASCII.GetBytes("192.54.67.8");
     buffer = new byte[4];
     buffer = BitConverter.GetBytes(senderIPBuffer.Length);
     this.networkStream.Write(buffer, 0, 4);
     this.networkStream.Flush();
     this.networkStream.Write(senderIPBuffer, 0, senderIPBuffer.Length);
     this.networkStream.Flush();
     //Sender Name + Size
     byte[] senderNameBuffer = Encoding.ASCII.GetBytes("James");
     buffer = new byte[4];
     buffer = BitConverter.GetBytes(senderNameBuffer.Length);
     this.networkStream.Write(buffer, 0, 4);
     this.networkStream.Flush();
     this.networkStream.Write(senderNameBuffer, 0, senderNameBuffer.Length);
     this.networkStream.Flush();
     //Command Target IP + Size
     byte[] targetIPBuffer = Encoding.ASCII.GetBytes("192.43.54.6");
     buffer = new byte[4];
     buffer = BitConverter.GetBytes(targetIPBuffer.Length);
     this.networkStream.Write(buffer, 0, 4);
     this.networkStream.Flush();
     this.networkStream.Write(targetIPBuffer, 0, targetIPBuffer.Length);
     this.networkStream.Flush();
     //Command MetaData + Size
     byte[] metaBuffer = Encoding.Unicode.GetBytes("Metadata contents");
     buffer = new byte[4];
     buffer = BitConverter.GetBytes(metaBuffer.Length);
     this.networkStream.Write(buffer, 0, 4);
     this.networkStream.Flush();
     this.networkStream.Write(metaBuffer, 0, metaBuffer.Length);
     this.networkStream.Flush();
    
    谢谢
    本文地址 :CodeGo.net/1106263/
    -------------------------------------------------------------------------------------------------------------------------
    1.SocketServer的具有类级变量“套接字” SocketServer的的构造函数创建一个套接字监听指定的端口上,并保存此作为sockets的价值 ListenSocketConnection呼吁Socket.Accept(良好),并保持连接的列表 错误:ReceiveDataListener正试图从被监听指定端口上的sockets,而不是由在ListenSocketConnection在接受电话被退回,个别sockets读来读 注:服务器在ReceiveDataListener权利在启动时(至少)抛出一个异常,在任何客户端端,甚至试图连接,因为sockets读者工人试图从套接字是在收听状态读取。 希望帮助-哈rhodes
    本文标题 :C#套接字(服务器)不会收取任何景致
    本文地址 :CodeGo.net/1106263/
    1. 如何用C#实时获取当前网络状态是否联网?如何用C#实现ADSL自动拨号
    2. 将数据传递给查看使用动作C#的MVC
    3. 求一个匹配URL的表达式,包括hppt和ftp的?
    4. 如何FUNC的属性Target <>设置?
    5. 請教大俠:怎麼樣在我們方本框中輸入這個格式“00.00%”
    6. 检测粗体,下划线在word文档中的文字和标题用C#SDK OPENXML
    7. 如何让OleDbDataAdapter一次执行2条sql语句
    8. 设置一个窗口,一次只能打开,除非需要
    9. 向教窗体隐藏和退出问题
    10. 如何找到客户端谁是登录我们的网站或浏览我们的网站的ip地址

     
    

    Copyright © 2017 CodeGo.net
    http://codego.net/xinwen/ 足球比分网 足球比分 医药招商网 邵阳县新闻