我必须在一个项目中使用TCP通信集成2个系统 - 开发了一个自定义协议 .
通过协议发送的消息如下所示:
MsgLength - 10 positions (in chars, not bytes)
MessageType - 20 positions
Message Number - 9 positions
Timestamp - 19 positions
version - 2 positions
Body - variable (depending on first field)
我正在研究Socket编程,但我想知道等待完整的msg到达的最佳方法是什么 . 可能我需要将字节转换为剩余的字符数 . 因为套接字API仅适用于字节 .
欢迎所有提示,代码示例,博客文章:-)
编辑:这是我的第一个版本的代码,我使用的是Async方法,因为多个客户端可以同时连接 .
private static void Listen()
{
while (true)
{
//TcpClient client = _listener.AcceptTcpClient();
allDone.Reset();
_listener.BeginAcceptTcpClient(new AsyncCallback(AcceptCallback), _listener);
allDone.WaitOne();
}
}
public static void AcceptCallback(IAsyncResult ar)
{
// Signal the main thread to continue.
allDone.Set();
// Get the socket that handles the client request.
//TcpListener listener = (TcpListener)ar.AsyncState;
TcpClient handler = _listener.EndAcceptTcpClient(ar);
// Create the state object.
StateObject state = new StateObject();
state.client = handler;
handler.GetStream().BeginRead(state.buffer, 0, StateObject.BufferSize, new AsyncCallback(ReadCallback), state);
}
public static void ReadCallback(IAsyncResult ar)
{
String content = String.Empty;
Encoding enc = Encoding.GetEncoding("ISO-8859-1");
// Retrieve the state object and the handler socket
// from the asynchronous state object.
StateObject state = (StateObject)ar.AsyncState;
TcpClient handler = state.client;
int bytesRead = handler.GetStream().EndRead(ar);
state.TotalHeaderBytesRead += bytesRead;
if (bytesRead == 60)
{
string header = enc.GetString(state.buffer);
Header h = HeaderParser.Parse(header);
//todo read the body
byte[] bodyBuffer = new byte[((HeaderPlaPo)h).Length - 60];
state.buffer = bodyBuffer;
handler.GetStream().BeginRead(state.buffer, 0, bodyBuffer.Length, new AsyncCallback(ReadBodyCallback), state);
Logger.Log(string.Format("received header {0}", header), System.Diagnostics.TraceLevel.Info);
}
else
{
// Not all data of header received. Get more.
handler.GetStream().BeginRead(state.buffer, 0, StateObject.BufferSize - state.TotalHeaderBytesRead, new AsyncCallback(ReadHeaderCallback), state);
}
}
public static void ReadBodyCallback(IAsyncResult ar)
{
Encoding enc = Encoding.GetEncoding("ISO-8859-1");
// Retrieve the state object and the handler socket
// from the asynchronous state object.
StateObject state = (StateObject)ar.AsyncState;
TcpClient handler = state.client;
int bytesRead = handler.GetStream().EndRead(ar);
int bytesRead = handler.GetStream().EndRead(ar);
state.TotalBodyBytesRead += bytesRead;
if (state.buffer.Length == state.TotalBodyBytesRead)
{// todo我们收到了所有的字符串body = enc.GetString(state.buffer); Logger.Log(string.Format(“received body {0}”,body),System.Diagnostics.TraceLevel.Info); } else {handler.GetStream() . BeginRead(state.buffer,bytesRead,state.buffer.Length - state.TotalBodyBytesRead,ReadBodyCallback,state); }}
public class StateObject {// Client socket . public TcpClient client = null; //接收缓冲区的大小 . public static int BufferSize = 60; //接收缓冲区 . public byte [] buffer = new byte [BufferSize]; //收到的数据字符串public StringBuilder sb = new StringBuilder(); //标头公共标头 Headers ;公共身体; public Int32 TotalBodyBytesRead; public Int32 TotalHeaderBytesRead; }
此代码适用于发送数据和关闭连接的客户端,但是当使用连接的客户端多次发送时,数据不会被读取 - >读取完整的主体后我应该关闭连接吗?
1 回答
你没有提到你使用的语言,我用Java提供的例子,如果你需要用其他语言让我知道 . 无论如何,你需要在一次关闭中读取60(10 20 9 19 2)个字节 . 将10个第一个字节(字符)转换为整数,然后将该字节数读入byte []数组 .
例如:
编辑:改为C#