【发布时间】:2013-11-21 00:43:00
【问题描述】:
请耐心等待,这是一个复杂的问题,而且它是一段很长的代码,但我已经花了大约两周的时间试图让它发挥作用,沮丧程度非常非常高。任何帮助表示赞赏!
我有一个基于套接字的 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
【问题讨论】:
标签: c# java state asyncsocket