C#异步套接字服务器没有收到来自Java客户端的响应

C#异步套接字服务器没有收到来自Java客户端的响应

问题描述:

忍让我,这是一个复杂的问题,它是一段很长的代码,但我已经拉了我的头发大约两个星期试图让这个工作,挫折水平非常高。任何帮助表示赞赏!C#异步套接字服务器没有收到来自Java客户端的响应

我有一个基于套接字的Java服务器&客户端使用基于XML的数据库。我正在用一个与MySQL数据库交谈的C#替换服务器。客户将保持原样,直到它也可以被替换,最早可能在明年晚些时候,所以认为它是半透明盒子(最好),而且是不变的。

我需要能够在新服务器上一次支持大约十几个Java客户端,如果我们扩展我们的设施,可能需要几十个。

获得客户端响应服务器需要相当长的一段时间,但硬编码服务器确实与客户端进行通信,尽管以非常暴力的方式。这是我对概念的证明,而且我认为将代码转换为异步服务器会比较简单,因为我不想使用它。那是大约两周前。我们在上周五举行了代码审查,以帮助我将硬编码的内容加入到异步服务器中。我已经取得了一些成功,客户端响应它与用户名的初始联系,但是任何进一步的通信都停止了(它应该发送基于XML的查询,并且服务器用基于XML的响应来响应)。

程序流程如下:

启动服务器;

启动客户端;

服务器发送: “Login:”,但是,这可能是从字面上任何

客户端发送: “USERNAME

服务器发送: “ACCEPTED

服务器发送: “ACCEPTED”(不知道为什么这是必要的,但客户端不响应第一个服务器发送,我不能改变它)。

客户端发送:<PCBDataBaseCMD><Search><PCBID>33844</PCBID></Search></PCBDataBaseCMD>

服务器发送:

<Executing/> 
<PCBDatabaseReply> 
    <SearchResult> 
     <SBE_PCB_Data PCBID='33844'> 
      <Creation ActionID='e2a7' User='DELLIOTTG:192.168.1.214' Date='2013-01-23T13:16:51' PCBID='33844'> 
       <PCBDrawing>10376A</PCBDrawing> 
       <AssemblyDrawing>41528F</AssemblyDrawing> 
       <Vendor>PCA</Vendor> 
       <PONumber>99999</PONumber> 
      </Creation> 
      <Assignment ActionID='e2c1' User='DELLIOTTG:192.168.1.228' Date='2013-01-23T15:30:00' PCBID='33844'> 
       <SBESerialNumber>04104743</SBESerialNumber> 
      </Assignment> 
     </SBE_PCB_Data> 
    </SearchResult> 
</PCBDatabaseReply> 

此XML将在客户端显示为预期。

重置&等待下一个客户端请求。

这里是硬编码服务器(这将编译原样):

using System; 
using System.IO; 
using System.Net; 
using System.Net.Sockets; 
using System.Text; 

class MyTcpListener 
{ 
    public static void Main() 
    { 
     Int32 port = 8955; 
     IPAddress localAddr = IPAddress.Parse("192.168.1.137"); 
     TcpListener server = null; 
     server = new TcpListener(localAddr, port); 
     server.Start(); 
     Socket socketForClient = server.AcceptSocket(); 
     NetworkStream stream = new NetworkStream(socketForClient); 
     System.IO.StreamWriter streamWriter = new System.IO.StreamWriter(stream); 
     System.IO.StreamReader streamReader = new System.IO.StreamReader(stream); 
     string response1 = @"<Executing/> 
      <PCBDatabaseReply> 
       <SearchResult> 
        <SBE_PCB_Data PCBID='33844'> 
         <Creation ActionID='e2a7' User='DELLIOTTG:192.168.1.214' Date='2013-01-23T13:16:51' PCBID='33844'> 
          <PCBDrawing>10376A</PCBDrawing> 
          <AssemblyDrawing>41528F</AssemblyDrawing> 
          <Vendor>PCA</Vendor> 
          <PONumber>99999</PONumber> 
         </Creation> 
         <Assignment ActionID='e2c1' User='DELLIOTTG:192.168.1.228' Date='2013-01-23T15:30:00' PCBID='33844'> 
          <SBESerialNumber>04104743</SBESerialNumber> 
         </Assignment> 
        </SBE_PCB_Data> 
       </SearchResult> 
      </PCBDatabaseReply>"; 
     try 
     { 
      while(true) 
      { 
       Console.WriteLine("Waiting for Client connection... "); 
       streamWriter.WriteLine("poke"); //this can literally be anything, just something to let the client know the server's there 
       streamWriter.Flush(); 
       string userName = streamReader.ReadLine(); 
       Console.WriteLine(userName); 
       streamWriter.WriteLine("ACCEPTED"); 
       streamWriter.Flush(); 
       streamWriter.WriteLine("ACCEPTED"); 
       streamWriter.Flush(); 
       string buffer = string.Empty; 
       bool sendFlag = true; 
       ASCIIEncoding encoder = new ASCIIEncoding(); 
       char[] c = new char[512]; 
       while (sendFlag) 
       {    
        streamReader.Read(c, 0, c.Length); 
        buffer += string.Join("", c); 
        streamReader.Read(c, 0, c.Length); 
        buffer += string.Join("", c); 
        Console.WriteLine(buffer); 
        if(streamReader.Peek() < 0) 
        { 
         sendFlag = false; 
        } 
        else 
        { 
         Console.WriteLine("Apparently not at the end?"); 
        } 
       }      
       Console.WriteLine("RECEIVED: " + buffer); 
       //} 
       Console.WriteLine("SEND: " + response1); 
       streamWriter.Write(response1); 
       streamWriter.Flush(); 
      } 
     } 
     catch(ObjectDisposedException ex) 
     { 
      Console.WriteLine("ObjectDisposedException: {0}", ex); 
     } 
     catch(SocketException e) 
     { 
      Console.WriteLine("SocketException: {0}", e); 
     } 
     finally 
     { 
      server.Stop(); 
      streamReader.Dispose(); 
      streamReader.Close(); 
     } 
     Console.WriteLine("\nHit enter to continue..."); 
     Console.Read(); 
    } 
} 

我已经转码成异步服务器,但我不得不承认比如何完美的默契少所有的部分一起工作,以及状态对象如何工作来引导流量。我认为通信可能在SendCallBack()模块中发生故障,因为我没有发送“停止接收”消息,或者可能是“继续传输”消息,我不确定。

这里是异步服务器(这个不会编译,它缺少很多MySql,命令行处理等代码,以缩短它的好处)。

public static IPAddress IpAddress { get; set; } 
    private static readonly ManualResetEvent AllDone = new ManualResetEvent(false); 

    public static IPEndPoint GetIpEndPoint() 
    { 
     IpAddress = Dns.GetHostEntry(Dns.GetHostName()).AddressList.FirstOrDefault(addr => addr.AddressFamily.ToString() == "InterNetwork"); 
     if (IpAddress != null) 
     { 
      IPEndPoint localEndPoint = new IPEndPoint(IpAddress, CommandLineOptions.Port); 
      return localEndPoint; 
     } 
     return null; 
    } 
    public class StateObject 
    { 
     public Socket workSocket = null; 
     public const int bufferSize = 1024; 
     public byte[] buffer = new byte[bufferSize]; 
     public string UserName { get; set; } 
     public string XmlContent { get; set; } 
     public StringBuilder sb = new StringBuilder(); 
     public StreamReader sr; 
     public StreamWriter sw; 
    } 
    public static void StartListening(IPEndPoint localEndPoint) 
    { 
     byte[] bytes = new Byte[1024]; 
     Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); 
     try 
     { 
      listener.Bind(localEndPoint); 
      listener.Listen(100); 
      while (true) 
      { 
       AllDone.Reset(); 
       Console.WriteLine("PCBDatabaseServer online awaiting a connection..."); 
       listener.BeginAccept(AcceptCallback, listener); 
       AllDone.WaitOne(); 
      } 
     } 
     catch (Exception e) 
     { 
      Log.Error(e.ToString()); 
     } 
     Console.WriteLine("\nPress ENTER to continue..."); 
     Console.Read(); 
    } 
    public static void AcceptCallback(IAsyncResult ar) 
    { 
     try 
     { 
      AllDone.Set(); 
      Socket listener = (Socket) ar.AsyncState; 
      Socket handler = listener.EndAccept(ar); 
      NetworkStream nwsHandle = new NetworkStream(handler); 
      StateObject acbState = new StateObject 
       { 
        workSocket = handler, 
        sw = new StreamWriter(nwsHandle) {AutoFlush = true}, 
        sr = new StreamReader(nwsHandle) 
       }; 
      acbState.sw.WriteLine("poke"); 
      handler.BeginReceive(acbState.buffer, 0, StateObject.bufferSize, 0, ReadCallback, acbState); 
      acbState.UserName = Encoding.UTF8.GetString(acbState.buffer); 
      Console.WriteLine(acbState.UserName); 
     } 
     catch (IOException ex) 
     { 
      Console.WriteLine(ex); 
     } 
    } 
    public static void ReadCallback(IAsyncResult ar) 
    { 
     try 
     { 
      StateObject rcbState = (StateObject) ar.AsyncState; 
      rcbState.sw.Write("ACCEPTED");//**this double call is required, the client has two ReadLine() statements, pretty sure the first write could be anything, and it only sees the second one, but I can't change the client** 
      rcbState.sw.Write("ACCEPTED"); 
      string testMeToo = string.Empty;//this is where I'm trying to capture the XML data from the client, which should end up in rcbState.XmlContent, but I'm flailing here trying to get this to work. 
      bool sendFlag = true; 
      char[] c = new char[512]; 
      while (sendFlag) 
      { 
       rcbState.sr.Read(c, 0, c.Length); 
       testMeToo = string.Join("", c); 
       rcbState.sr.Read(c, 0, c.Length); 
       testMeToo += string.Join("", c); 
       Console.WriteLine(testMeToo); 
       if (rcbState.sr.Peek() < 0) 
       { 
        sendFlag = false; 
       } 
       else 
       { 
        Console.WriteLine("Apparently not at the end?"); 
       } 
      } 
      Console.WriteLine("RECEIVED: " + testMeToo); 
      rcbState.workSocket.BeginReceive(rcbState.buffer, 0, StateObject.bufferSize, 0, AcceptCallback, rcbState); 
      rcbState.XmlContent = Encoding.UTF8.GetString(rcbState.buffer); 
      Console.WriteLine("XML: " + rcbState.XmlContent); 
      rcbState.XmlContent += Encoding.UTF8.GetString(rcbState.buffer); 
      Console.WriteLine("XML: " + rcbState.XmlContent); 
      int bytesRead = rcbState.workSocket.EndReceive(ar); 
      string content = string.Empty; 
      //**things break down here, you can ignore this if statement** 
      if (bytesRead > 0) 
      { 
       while (bytesRead > 0) 
       { 
        rcbState.sb.Append(Encoding.ASCII.GetString(rcbState.buffer, 0, bytesRead)); 
        content = rcbState.sb.ToString(); 
       } 
       if (true) 
       { 
        Console.WriteLine("Read {0} bytes from socket. \nData : {1}", content.Length, content); 
        Console.WriteLine(content); 
        Send(rcbState.workSocket, content); 
       } 
       else 
       { 
        rcbState.workSocket.BeginReceive(rcbState.buffer, 0, StateObject.bufferSize, 0, ReadCallback, rcbState); 
       } 
      } 
     } 
     catch (Exception ex) 
     { 
      Console.WriteLine(ex); 
     } 
    } 
    private static void Send(Socket handler, String data) 
    { 
     byte[] byteData = Encoding.ASCII.GetBytes(data); 
     NetworkStream nwsHandle = new NetworkStream(handler); 
     StateObject sendState = new StateObject 
      { 
       workSocket = handler, 
       sw = new StreamWriter(nwsHandle) {AutoFlush = true} 
      }; 
     sendState.sw.Write(data); 
    } 
    //here is where I think the communication is breaking down, I think the client may be waiting for some signal to tell it to send the next bit, but I can't figure out what that may be. 
    private static void SendCallback(IAsyncResult ar) 
    { 
     try 
     { 
      Socket listener = (Socket)ar.AsyncState; 
      Socket handler = listener.EndAccept(ar); 
      NetworkStream nwsListen = new NetworkStream(listener); 
      NetworkStream nwsHandle = new NetworkStream(handler); 
      StateObject scbState = new StateObject 
      { 
       workSocket = handler, 
       sw = new StreamWriter(nwsHandle) { AutoFlush = true }, 
       sr = new StreamReader(nwsListen) 
      }; 
      int bytesSent = scbState.workSocket.EndSend(ar); 
      Console.WriteLine("Sent {0} bytes to client.", bytesSent); 
      handler.Shutdown(SocketShutdown.Both); 
      handler.Close(); 
     } 
     catch (Exception e) 
     { 
      Log.Error(e.ToString()); 
     } 
    } 
    #endregion 
} 

}

这里有一些链接我的研究,首先是一个相关的问题,而我回信说:
Source-less black box client

C#<> Java socket communications

How to write a scalable TCP/IP based server

C# High Performance Socket Code

夫妇的事情要考虑:

  1. 你AllDone.Wait()是怎么回事,而你继续与客户交谈,以阻止你接受线程。这种方式违背了异步I/O的目的,因为您希望服务器在接受连接时立即返回监听连接,否则您的处理将被序列化。

  2. BeginReceive(...)将立即返回,并且您可能在读取操作未完成时将数据从读取缓冲区分配给变量。

  3. 在您的接收回调中,看起来您正在发出更多的异步读取(BeginReceive)。不确定这是你的意图,因为你已经在与服务器的主接受线程分离的线程中运行。您可能需要考虑使用rcbState.workSocket.Receive(...)而不是BeginReceive(),该方法完成回到您的接受回调,该回调应该用于接受未完成读取的连接。因此,看起来逻辑是错误的。

所以我的整体建议是,一旦你进入你的接受回调使用同步读取和对新的socket你写,因为它似乎从我可以告诉你有一系列的客户机/服务器交互完成“交易”。一旦接受来自客户端的连接,似乎没有任何价值做额外的异步读/写操作。你当时只是在做异步读/写操作而让自己感到困惑。

+0

感谢您的建议,我会第一个承认我对此感到困惑!今天我会更多地讨论这个问题,看看我能否利用你的意见。我认为您可能会遇到有关异步和同步读取和写入事务的问题。我当然希望如此,我已经准备好做好这件事了。 – delliottg