日期:2014-05-20  浏览次数:20920 次

请教关于TcpClient的问题?
问题描述:
我在做一个跟GPS有关的软件。现在使用的是一种车机协议。他提供给我一个网关。需要我去连接它。这个就是对这个网关的描述:“本文档定义第三方与飞田通信网关通讯(以下简称为网关)消息格式。与网关通讯采用标准TCP/IP协议。第三方以Socket   Client     身份连接到网关,发送与接受的字符串以   UTF-8   格式编码。”

苦恼:车辆发送GPS信息给这个网关后,不知道是他主动发给我还是我主动找他要。我对TCP不熟悉。我现在想出来的办法是:我Connect网关,然后取得LocalEndPoint,然后监听这个端口。但是怎么搞都有错。

private   void   Run()
{
try
{
IPAddress   address   =   IPAddress.Parse( "192.168.1.118 ");
IPEndPoint   endPoint   =   new   IPEndPoint(address,8081);
Socket   sock   =   new   Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
try
{
sock.Connect(endPoint);
}
catch(SocketException)
{
this.richTextBox1.Text   +=   "无法连接 "+ "\r\n ";
}
if(sock.Connected)
{
this.richTextBox1.Text   +=   Convert.ToString(sock.LocalEndPoint);
sock.Bind(sock.LocalEndPoin);
sock.Listen(50);
Socket   newSock   =   sock.Accept();
this.richTextBox1.Text+=newSock.LocalEndPoint;
while(true)
{
byte[]   messageByte   =   new   byte[64];
newSock.Receive(messageByte);
string   message   =   System.Text.UnicodeEncoding.Unicode.GetString(messageByte);
this.richTextBox1.Text+=message;
}
}
}
catch(Exception   ex)
{
this.richTextBox1.Text   +=   ex.Message;
}

------解决方案--------------------
TcpClient myClient;
Byte[] RecvBuffer = new Byte[1024];
用开始异步接受数据
myClient.GetStream().BeginRead(RecvBuffer, 0, 1024, new AsyncCallback(GetCommand), null);


private void GetCommand(IAsyncResult ar)
{
int intCount;
try
{
//Lock the Client Stream
lock (myClient.GetStream())
{
//Receive the Bytes
intCount = myClient.GetStream().EndRead(ar);
}
if (intCount < 1)
{
//If a value less than 1 received that means that
//client disconnected
myClient.Close();
//raise the Disconnected Event
}
//Do Something to Do with the Packet
}

//Restart
lock (myClient.GetStream())
{
myClient.GetStream().BeginRead(RecvBuffer, 0, 1024, new AsyncCallback(GetCommand), null);
}
}
catch (Exception ex)
{
}
}

这样就可以不断接收