使用异步套接字编程发送二进制数据并读取其值
本文关键字:数据 读取 二进制 异步 套接字 编程 | 更新日期: 2023-09-27 18:11:45
我正在尝试从我的客户端向服务器发送数据。客户端向服务器发送消息,每条消息是36 bytes
,并且在此消息中每4字节是一个字段,并且在服务器部分,我应该能够从客户端发送的消息中检测到该字段。假设我有这个数据:
A=21
B=32
c=43
D=55
E=75
F=73
G=12
H=14
M=12
在客户端,我应该发送这个值作为一个单一的消息。你可以看到我的消息有9个字段,每个字段是4 byte integer
,所有的消息是36 byte
。
所以在服务器部分,当收到消息时,我应该能够分离消息并找到字段的值。
在客户端应用程序中,我使用这个结构向我的服务器发送消息:
m_clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
// Cet the remote IP address
IPAddress ip = IPAddress.Parse(GetIP());
int iPortNo = System.Convert.ToInt16("12345");
// Create the end point
IPEndPoint ipEnd = new IPEndPoint(ip, iPortNo);
// Connect to the remote host
m_clientSocket.Connect(ipEnd);
if (m_clientSocket.Connected)
{
Object objData = ?!!!!;//My message
byte[] byData = System.Text.Encoding.ASCII.GetBytes(objData.ToString());
if (m_clientSocket != null)
{
m_clientSocket.Send(byData);
}
Thread.Sleep(4000);
}
}
在服务器部分,我使用这个代码来接收数据:
public void OnDataReceived(IAsyncResult asyn)
{
try
{
SocketPacket socketData = (SocketPacket)asyn.AsyncState;
int iRx = 0;
// Complete the BeginReceive() asynchronous call by EndReceive() method
// which will return the number of characters written to the stream
// by the client
iRx = socketData.m_currentSocket.EndReceive(asyn);
char[] chars = new char[iRx + 1];
System.Text.Decoder d = System.Text.Encoding.UTF8.GetDecoder();
int charLen = d.GetChars(socketData.dataBuffer,
0, iRx, chars, 0);
System.String szData = new System.String(chars);
MessageBox.Show(szData);
// Continue the waiting for data on the Socket
WaitForData(socketData.m_currentSocket);
}
catch (ObjectDisposedException)
{
System.Diagnostics.Debugger.Log(0, "1", "'nOnDataReceived: Socket has been closed'n");
}
catch (SocketException se)
{
}
}
下面是我的服务器代码的另一部分:
public void OnClientConnect(IAsyncResult asyn)
{
try
{
// Here we complete/end the BeginAccept() asynchronous call
// by calling EndAccept() - which returns the reference to
// a new Socket object
m_workerSocket[m_clientCount] = m_mainSocket.EndAccept(asyn);
// Let the worker Socket do the further processing for the
// just connected client
WaitForData(m_workerSocket[m_clientCount]);
// Now increment the client count
++m_clientCount;
// Display this client connection as a status message on the GUI
String str = String.Format("Client # {0} connected", m_clientCount);
// Since the main Socket is now free, it can go back and wait for
// other clients who are attempting to connect
m_mainSocket.BeginAccept(new AsyncCallback(OnClientConnect), null);
}
catch (ObjectDisposedException)
{
System.Diagnostics.Debugger.Log(0, "1", "'n OnClientConnection: Socket has been closed'n");
}
}
public class SocketPacket
{
public System.Net.Sockets.Socket m_currentSocket;
public byte[] dataBuffer = new byte[36];
}
在我的form_load
服务器部分,我有这个代码:
ipaddress = GetIP();
// Check the port value
string portStr = "12345";
int port = System.Convert.ToInt32(portStr);
// Create the listening socket...
m_mainSocket = new Socket(AddressFamily.InterNetwork,
SocketType.Stream,
ProtocolType.Tcp);
IPEndPoint ipLocal = new IPEndPoint(IPAddress.Any, port);
// Bind to local IP Address...
m_mainSocket.Bind(ipLocal);
// Start listening...
m_mainSocket.Listen(4);
// Create the call back for any client connections...
m_mainSocket.BeginAccept(new AsyncCallback(OnClientConnect), null);
实际上我正在尝试实现这个链接:
http://www.codeguru.com/csharp/csharp/cs_misc/sampleprograms/article.php/c7695/Asynchronous-Socket-Programming-in-C-Part-I.htm我的问题是我怎么能发送我的消息作为一个36字节通过客户端,并从服务器获得和分离?
每四个字节是一个字段,我应该能够得到这个值
你做错了。如果要传输二进制数据,请不要将其编码为字符串。有多种方法可以做到这一点:
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct Msg
{
public int A, B, C, D, E, F, G, H, M;
}
然后使用Marshal
类来获取字节。这将使您在连线数据上得到小端数据。
另一个方法是使用BinaryWriter
。同样的,小端数据,除非你自己转换它或使用BinaryWriter
的替代版本。
然后,使用NetworkStream
要容易得多,因为这个类将为您处理数据包碎片。下面是使用BinaryWriter
方法的发送代码:
using (var stream = new NetworkStream(stocket))
{
var writer = new BinaryWriter(stream);
writer.Write(21);
writer.Write(32);
// etc
}
在客户端使用NetworkStream
和BinaryReader
也是一样的。
注意:你可以使用异步I/O与NetworkStream
使用async/await特性。
似乎所有你需要的是2种方法转换整数到字节数组,反之亦然:
byte[] packet = CreateMessage(21,32,43,55,75,73,12,14,12);
//send message
//recv message and get ints back
int[] ints = GetParameters(packet);
…
public byte[] CreateMessage(params int[] parameters)
{
var buf = new byte[parameters.Length * sizeof(int)];
for (int i = 0; i < parameters.Length; i++)
Array.Copy(BitConverter.GetBytes(parameters[i]), 0, buf, i * sizeof(int), sizeof(int));
return buf;
}
public int[] GetParameters(byte[] buf)
{
var ints = new int[buf.Length / sizeof(int)];
for (int i = 0; i < ints.Length; i++)
ints[i] = BitConverter.ToInt32(buf, i * sizeof(int));
return ints;
}