gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 15:23:39 25 4
gpt4 key购买 nike

请耐心等待,这是一个复杂的问题,而且是一段很长的代码,但我已经花了大约两周的时间试图让它发挥作用,挫败感非常非常高。如有任何帮助,我们将不胜感激!

我有一个基于套接字的 Java 服务器和客户端,它使用基于 XML 的数据库。我正在将服务器替换为基于 C# 的、与 MySQL 数据库通信的服务器。客户端将保持原样,直到它也可以被替换(最早可能在明年年底),因此将其视为半透明盒子(最多)并且不可变。

我需要能够使用新服务器同时支持大约十几个 Java 客户端,如果我们扩展我们的设施,可能会支持几十个。

花了相当长的时间让客户端响应服务器,但是硬编码的服务器确实与客户端进行通信,尽管是以一种非常暴力的方式。这是我的概念证明,我认为使用 MSDN example 将代码转换为异步服务器相对简单。我就走了。那是大约两周前的事了。上周五我们进行了代码审查,以帮助我将硬编码的内容放入异步服务器中。我已经取得了一些成功,客户端按照预期响应其与用户名的初始联系,但任何进一步的通信都停止了(它应该发送基于 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(),它会完成返回到您的接受回调,该回调应该用于接受连接而不是完成读取。由此看来,逻辑完全错误。

所以我的总体建议是,一旦您进入 Accept 回调,请在您获得的新套接字上使用同步读取和写入,据我所知,您将进行一系列客户端/服务器交互来完成“交易”。一旦接受来自客户端的连接,进行额外的异步读/写似乎没有任何值(value)。你只是因为当时进行异步读/写而让自己感到困惑。

关于C# 异步套接字服务器未收到来自 Java 客户端的响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20110238/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com