客户可以';无法从服务器(C#)读取多条消息
我正在尝试制作一个简单的客户机-服务器程序来帮助学习网络编程。我的目标是建立一个在线象棋游戏,但现在我只是想做的基础。我已经从在线来源(MSDN)拼凑了一些代码,我认为它们都可以正常工作。以下是场景: 客户端向服务器发送测试消息 服务器回显响应客户可以';无法从服务器(C#)读取多条消息,c#,sockets,tcp,server,client,C#,Sockets,Tcp,Server,Client,我正在尝试制作一个简单的客户机-服务器程序来帮助学习网络编程。我的目标是建立一个在线象棋游戏,但现在我只是想做的基础。我已经从在线来源(MSDN)拼凑了一些代码,我认为它们都可以正常工作。以下是场景: 客户端向服务器发送测试消息 服务器回显响应 客户端读取响应并显示测试消息 客户端向服务器发送新消息 服务器回显响应 客户端显示测试消息 正确的输出应如下所示: 客户端向服务器发送测试消息 服务器回显响应 客户端读取响应并显示测试消息 客户端向服务器发送新消息 服务器回显响应 客户端显示新消息 感谢
客户端读取响应并显示测试消息
客户端向服务器发送新消息 服务器回显响应
客户端显示测试消息 正确的输出应如下所示: 客户端向服务器发送测试消息 服务器回显响应
客户端读取响应并显示测试消息
客户端向服务器发送新消息 服务器回显响应
客户端显示新消息 感谢您的一切帮助 以下是客户的相关部分:
private void OnlineButton_Click(object sender, EventArgs e)
{
// Connect to a remote device.
try
{
// Create a TCP/IP socket.
client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
// Connect to the remote endpoint.
client.BeginConnect(remoteEP, new AsyncCallback(ConnectCallback), client);
connectDone.WaitOne();
// Send test data to the remote device.
Send(client, "This is a test<EOF>");
sendDone.WaitOne();
// Receive the response from the remote device.
Receive(client);
receiveDone.WaitOne();
msg("Response received: " + response);
}
catch (Exception ex)
{
msg(ex.ToString());
}
msg("Client started, connected to: " + client.RemoteEndPoint.ToString());
sessionHandler(2);
}
public void msg(string mesg)
{
ServerMessages.Text = ServerMessages.Text + Environment.NewLine + " >> " + mesg;
}
public void sessionHandler(Int32 mode)
{
switch (mode)
{
case 1:
msg("Starting AI program...");
break;
case 2:
// Create a TCP/IP socket.
client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
// Connect to the remote endpoint.
client.BeginConnect(remoteEP, new AsyncCallback(ConnectCallback), client);
connectDone.WaitOne();
Send(client, "Play Online<EOF>");
sendDone.WaitOne();
Receive(client);
receiveDone.WaitOne();
msg("Response received: " + response);
msg("Pairing with another player...");
break;
case 3:
msg("Replaying selected game...");
break;
default:
msg("Error handling request...");
break;
}
}
private void online按钮\u单击(对象发送者,事件参数e)
{
//连接到远程设备。
尝试
{
//创建TCP/IP套接字。
client=newsocket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
//连接到远程端点。
BeginConnect(remoteEP,新的异步回调(ConnectCallback),client);
connectDone.WaitOne();
//将测试数据发送到远程设备。
发送(客户端,“这是一个测试”);
sendDone.WaitOne();
//从远程设备接收响应。
接收(客户);
receiveDone.WaitOne();
msg(“收到的响应:”+响应);
}
捕获(例外情况除外)
{
味精(例如ToString());
}
msg(“客户端已启动,连接到:”+Client.RemoteEndPoint.ToString());
会话处理程序(2);
}
公共无效消息(字符串mesg)
{
ServerMessages.Text=ServerMessages.Text+Environment.NewLine+“>>”+mesg;
}
public void sessionHandler(Int32模式)
{
开关(模式)
{
案例1:
msg(“启动AI程序…”);
打破
案例2:
//创建TCP/IP套接字。
client=newsocket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
//连接到远程端点。
BeginConnect(remoteEP,新的异步回调(ConnectCallback),client);
connectDone.WaitOne();
发送(客户端,“在线播放”);
sendDone.WaitOne();
接收(客户);
receiveDone.WaitOne();
msg(“收到的响应:”+响应);
msg(“与其他玩家配对…”);
打破
案例3:
msg(“重放选定的游戏…”);
打破
违约:
msg(“错误处理请求…”);
打破
}
}
这是服务器:
// State object for reading client data asynchronously
public class StateObject
{
// Client socket.
public Socket workSocket = null;
// Size of receive buffer.
public const int BufferSize = 1024;
// Receive buffer.
public byte[] buffer = new byte[BufferSize];
// Received data string.
public StringBuilder sb = new StringBuilder();
}
public class AsynchronousSocketListener
{
// Thread signal.
public static ManualResetEvent allDone = new ManualResetEvent(false);
public AsynchronousSocketListener()
{
}
public static void StartListening()
{
// Data buffer for incoming data.
byte[] bytes = new Byte[1024];
IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Any, 8888);
// Create a TCP/IP socket.
Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
// Bind the socket to the local endpoint and listen for incoming connections.
try
{
listener.Bind(localEndPoint);
listener.Listen(100);
while (true)
{
// Set the event to nonsignaled state.
allDone.Reset();
// Start an asynchronous socket to listen for connections.
Console.WriteLine("Waiting for a connection...");
listener.BeginAccept(new AsyncCallback(AcceptCallback), listener);
// Wait until a connection is made before continuing.
allDone.WaitOne();
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
Console.WriteLine("\nPress ENTER to continue...");
Console.Read();
}
public static void AcceptCallback(IAsyncResult ar)
{
// Signal the main thread to continue.
allDone.Set();
// Get the socket that handles the client request.
Socket listener = (Socket)ar.AsyncState;
Socket handler = listener.EndAccept(ar);
// Create the state object.
StateObject state = new StateObject();
state.workSocket = handler;
handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReadCallback), state);
}
public static void ReadCallback(IAsyncResult ar)
{
String content = String.Empty;
// Retrieve the state object and the handler socket
// from the asynchronous state object.
StateObject state = (StateObject)ar.AsyncState;
Socket handler = state.workSocket;
// Read data from the client socket.
int bytesRead = handler.EndReceive(ar);
if (bytesRead > 0)
{
// There might be more data, so store the data received so far.
state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, bytesRead));
// Check for end-of-file tag. If it is not there, read
// more data.
content = state.sb.ToString();
if (content.IndexOf("<EOF>") > -1)
{
// All the data has been read from the
// client. Display it on the console.
Console.WriteLine("Read {0} bytes from socket. \n Data : {1}", content.Length, content);
// Echo the data back to the client.
Send(handler, content);
}
else
{
// Not all data received. Get more.
handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReadCallback), state);
}
}
}
private static void Send(Socket handler, String data)
{
// Convert the string data to byte data using ASCII encoding.
byte[] byteData = Encoding.ASCII.GetBytes(data);
// Begin sending the data to the remote device.
handler.BeginSend(byteData, 0, byteData.Length, 0, new AsyncCallback(SendCallback), handler);
}
private static void SendCallback(IAsyncResult ar)
{
try
{
// Retrieve the socket from the state object.
Socket handler = (Socket)ar.AsyncState;
// Complete sending the data to the remote device.
int bytesSent = handler.EndSend(ar);
Console.WriteLine("Sent {0} bytes to client.", bytesSent);
handler.Shutdown(SocketShutdown.Both);
handler.Close();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
public static int Main(String[] args)
{
StartListening();
return 0;
}
//异步读取客户端数据的状态对象
公共类状态对象
{
//客户端套接字。
公共套接字工作组=null;
//接收缓冲区的大小。
public const int BufferSize=1024;
//接收缓冲区。
公共字节[]缓冲区=新字节[BufferSize];
//接收到的数据字符串。
公共StringBuilder sb=新StringBuilder();
}
公共类异步SocketListener
{
//线程信号。
public static ManualResetEvent allDone=新的ManualResetEvent(false);
公共异步SocketListener()
{
}
公共静态侦听()
{
//输入数据的数据缓冲区。
字节[]字节=新字节[1024];
IPEndPoint localEndPoint=新的IPEndPoint(IPAddress.Any,8888);
//创建TCP/IP套接字。
套接字侦听器=新套接字(AddressFamily.InterNetwork、SocketType.Stream、ProtocolType.Tcp);
//将套接字绑定到本地端点并侦听传入连接。
尝试
{
Bind(localEndPoint);
听,听(100);
while(true)
{
//将事件设置为非信号状态。
全部完成。重置();
//启动异步套接字以侦听连接。
Console.WriteLine(“等待连接…”);
beginacept(新的异步回调(AcceptCallback),listener);
//等待连接完成后再继续。
全部完成。WaitOne();
}
}
捕获(例外e)
{
Console.WriteLine(如ToString());
}
Console.WriteLine(“\n按ENTER继续…”);
Console.Read();
}
公共静态无效接受回调(IAsyncResult ar)
{
//向主线程发出继续的信号。
allDone.Set();
//获取处理客户端请求的套接字。
套接字侦听器=(套接字)ar.AsyncState;
套接字处理程序=listener.EndAccept(ar);
//创建状态对象。
StateObject状态=新的StateObject();
state.workSocket=处理程序;
BeginReceive(state.buffer,0,StateObject.BufferSize,0,新异步回调(ReadCallback),state);
}
公共静态void ReadCallback(IAsyncResult ar)
{
String content=String.Empty;
//检索状态对象和处理程序套接字
//从异步状态对象。
StateObject状态=(StateObject)ar.AsyncState;
套接字处理程序=state.workSocket;
//从客户端套接字读取数据。
int bytesRead=handler.EndReceive(ar);
如果(字节读取>0)
{
//可能会有更多数据,因此请存储到目前为止收到的数据。
state.sb.Append(Encoding.ASCII.GetString(state.buffer,0,bytesRead));
//检查文件结尾标记。如果不存在,请读取
//更多数据。
content=state.sb.ToString();