c# socket传输struct类型
data结构体类型
public struct datas
{
public string test1;
public string test2;
}
//socket服务器端
public void SocketServer()
{
Socket listener = new Socket(AddressFamily.InterNetwork,
SocketType.Stream,
ProtocolType.Tcp);
listener.Bind(new IPEndPoint(getLocalmachineIPAddress(), 2323));
listener.Listen(10);
while (true)
{
Socket socket = listener.Accept();
string receivedValue = string.Empty;
while (true)
{
byte[] receivedBytes = new byte[1024];
int numBytes = socket.Receive(receivedBytes);
Console.WriteLine("Receiving .");
receivedValue += Encoding.ASCII.GetString(receivedBytes,
0, numBytes);
if (receivedValue.IndexOf("[FINAL]") > -1)
{
break;
}
}
byte[] buffer = new byte[1024000];
if (receivedValue.Contains("get gateway rooms"))
{
MemoryStream mStream = new MemoryStream();
BinaryFormatter bf = new BinaryFormatter();
datas sendData;
sendData.m_DictRooms = FormMain.DictRooms;
sendData.m_DictRoomNameText = FormMain.DictRoomNameText;
bf.Serialize(mStream, sendData);
mStream.Flush();
mStream.Position = 0;
mStream.Read(buffer, 0, buffer.Length);
}
//string replyValue = "Message successfully received.";
//byte[] replyMessage = Encoding.ASCII.GetBytes(replyValue);
socket.Send(buffer);
socket.Shutdown(SocketShutdown.Both);
socket.Close();
}
listener.Close();
}
//socket客户端
private void socketClient(object sender, EventArgs e)
{
if (comboBoxGateway.SelectedItem != null)
{
byte[] receivedBytes = new byte[1024000];
IPHostEntry ipHost = Dns.Resolve(comboBoxGateway.SelectedItem.ToString());
IPAddress ipAddress = ipHost.AddressList[0];
IPEndPoint ipEndPoint = new IPEndPoint(ipAddress, 2323);
Socket sk = new Socket(AddressFamily.InterNetwork,
SocketType.Stream,
ProtocolType.Tcp);
sk.Connect(ipEndPoint);
string sendingMessage = "get gateway rooms";
byte[] forwardMessage = Encoding.ASCII.GetBytes(sendingMessage
+ "[FINAL]");
sk.Send(forwardMessage);
int totalBytesReceived = sk.Receive(receivedBytes);
MemoryStream mStream = new MemoryStream();
//ReceiveDatas = bf.Deserialize(receivedBytes,mStream );
mStream.Write(receivedBytes, 0, receivedBytes.Length);
mStream.Flush();
mStream.Position = 0;
BinaryFormatter bf = new BinaryFormatter();
if (mStream.Capacity > 0)
{
datas receiveDatas = (datas)bf.Deserialize(mStream);
}
sk.Shutdown(SocketShutdown.Both);
sk.Close();
//加载新选择的网关房间
InitializeSelectRoomsTab();
}
}