忍受我,这是一个复杂的问题,这是一段很长的代码,但是我已经把头发拉了大约两个星期试图让它发挥作用,挫折程度非常高。任何帮助表示赞赏!
我有一个基于套接字的Java服务器&使用基于XML的数据库的客户端。我正在用一个与MySQL数据库对话的基于C#的服务器替换服务器。客户端将保持原样,直到它也可以被替换,可能最早在明年年底,所以考虑它是半透明的盒子(充其量),并且是不可变的。
我需要能够使用新服务器一次支持大约十几个Java客户端,如果我们扩展我们的设施,可能需要几十个。
让客户端响应服务器需要相当长的时间,但硬编码服务器确实与客户端进行通信,尽管以非常强力的方式。这是我的概念证明,我认为使用MSDN example& amp;将代码转换为异步服务器相对简单。我走了大约两周前。我们上周五进行了代码审查,以帮助我将硬编码的内容输入异步服务器。我已经取得了一些成功,客户端响应它与用户名的初始联系,但任何进一步的通信都停止了(它应该发送基于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将按预期显示在客户端中。
重置&amp;等待下一个客户请求。
这是硬编码服务器(这将按原样编译):
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
答案 0 :(得分:0)
要考虑的事情:
当您与客户进行对话时,您的AllDone.Wait()将阻止您的接受线程。这种方式违背了异步I / O的目的,因为您希望服务器在接受连接后立即返回侦听连接,否则您的处理将被序列化。
BeginReceive(...)将立即返回,并且当读取可能不完整时,您将数据从读取缓冲区分配给变量。
在您的接收回调中,您似乎发出了更多异步读取(BeginReceive)。不确定这是你想要的,因为你已经在一个与服务器的主接受线程分开的线程中运行。您可能需要考虑使用rcbState.workSocket.Receive(...)而不是BeginReceive(),顺便说一下,它将返回到您的接受回调,该回调应该用于接受未完成读取的连接。因此,似乎逻辑完全错误。
所以我的总体建议是,一旦你进入你的Accept回调,就可以看到新套接字上的同步读写,从我所知道的,你有一系列的客户/服务器交互来完成一个“交易”。一旦接受来自客户端的连接,执行额外的异步读/写似乎没有任何价值。你只是在那时通过异步读/写来混淆自己。