NetworkStream 在网络中进行传输的数据流,传输的数据必须传入数据流中,才能与svr端进行数据交互。
首先客户端先获取用于发送信息的流,然后将要发送的信息存入byte[] 数组中(数据必须是byte[] 才能够写入流中),最后就是写入传输的数据流,发送
直接上客户端代码:
//设置TCP连接对象
TcpClient connection = new TcpClientWithTimeout("10.120.230.21", port, 5000).Connect();
Console.WriteLine("{0}----->{1}", connection.Client.LocalEndPoint, connection.Client.RemoteEndPoint);
NetworkStream stream = connection.GetStream();
String factoryName = this.grdVersionList.ActiveRow.Cells["FACTORYNAME"].Text;
String productSpecName = this.grdVersionList.ActiveRow.Cells["PRODUCTSPECNAME"].Text;
String modelType = this.grdVersionList.ActiveRow.Cells["MODELTYPE"].Text;
String version = this.grdVersionList.ActiveRow.Cells["VERSION"].Text;
//组装Json格式对象
string jsonMessage = "{\"FACTORYNAME\":\"" + factoryName + "\",\"PRODUCTSPECNAME\":\"" + productSpecName + "\",\"MODELTYPE\":\"" + modelType + "\",\"VERSION\":\"" + version + "\"}";
//将信息存入缓存中
byte[] to_send = Encoding.UTF8.GetBytes(jsonMessage);
stream.Write(to_send, 0, to_send.Length);
string rcdata = "";
while (true)
{
try
{
byte[] readbuf = new byte[2048]; // you must allocate space first
int datalen = connection.Available;
stream.ReadTimeout = 90000; // 90 seconds timeout on the read
stream.Read(readbuf, 0, datalen);
rcdata = ASCIIEncoding.ASCII.GetString(readbuf).Substring(0, datalen);
//收到Svr端回复后跳出死循环,否则在Timeout进入异常块后跳出死循环
if (datalen > 0)
{
Console.WriteLine("receive:" + rcdata);
break;
}
}
catch (Exception ex)
{
ExceptionMsgBox.This.ShowMessageBox(MessageType.Warning, "服务器未响应;"+ex, this.Text);
break;
}
}
// 关闭连接
stream.Close();
connection.Close();
Svr端代码
开启服务:
IPAddress ip = new IPAddress(new byte[] { 127, 1, 1, 1 });
TcpListener server = new TcpListener(ip, 8005);
server.Start();//服务端启动侦听
TcpClient client = server.AcceptTcpClient();//接受发起连接对象的同步方法
解包
NetworkStream dataStream=client.GetStream();
byte[] buffer=new byte[8192];
int dataSize=dataStream.Read(buffer,0,8192);
Console.write(Encoding.default.GetString(buffer,0,dataSize));