我正在尝试从我的客户端向服务器发送数据。客户端向服务器发送消息,每条消息都是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);
实际上我正在尝试实现此链接:
我的问题是如何通过客户端将我的消息发送为36字节,并将其与服务器分开?
每四个字节是一个字段,我应该能够得到这个值。
答案 0 :(得分:2)
你做错了。如果要传输二进制数据,请不要将其编码为字符串。有多种方法可以做到这一点:
[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
在客户端进行同样的事情。
注意:您可以使用async / await功能将NetworkStream
与异步I / O一起使用。
答案 1 :(得分:1)
似乎所有你需要的是将整数转换为字节数组的两种方法,反之亦然:
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;
}