关于Socket通信怎么做啊
前段时间做串口通信,主要就是一些发送指令,做完后,老板说要用socket通信也做上,用到TCP通信,请问各位要怎么做,有链接也可以。先谢谢大家了。帮顶给分。
[解决办法]
http://blog.csdn.net/neusoft06/article/details/9113227
希望能帮到你
[解决办法]
100分啊,不错,给你段代码,刚写的~~
#region 监听连接
private void RecConn()
{
tempread = new TcpListener(portId);
tempread.Start();
while (true)
{
Thread.Sleep(2000);
try
{
stRead = tempread.AcceptSocket();
}
catch
{
continue;
}
tempRemoteEP = stRead.RemoteEndPoint;
tempRemoteIP = (IPEndPoint)tempRemoteEP;
tcpConnect = true;
string staIp = tempRemoteIP.Address.ToString();
string staName = IniFile.IniReadValue("集控站IP", staIp, "CenterFlag");
MessageBox.Show(string.Format("{0}站点连接主机", staName));
try
{
thredSendHeart.Start();
}
catch
{
thredSendHeart.Resume();
}
try
{
threadMonitor.Start();
}
catch
{
threadMonitor.Resume();
}
}
}
#endregion
#region 监听线程执行函数
private void ReceiveMessage()
{
while (tcpConnect)
{
thredRecConn.Suspend();
byte[] buffer=new byte[1050];
byte[] receiveBytes;
try
{
recDataLength = stRead.ReceiveFrom(buffer, ref tempRemoteEP);
receiveBytes = new byte[recDataLength];
for (int i = 0; i < recDataLength; i++)
{
receiveBytes[i] = buffer[i];
}
}
catch
{
continue;
}
if (recDataLength == 0)
{
MessageBox.Show("网络异常——断开连接");
tcpConnect = false;
thredRecConn.Resume();
try
{
thredSendHeart.Suspend();
}
catch
{ }
try
{
threadMonitor.Suspend();
}
catch
{ }
continue;
}
//挂起心跳检测线程
if (thredSendHeart.ThreadState == ThreadState.Running)
{
thredSendHeart.Suspend();
}
for (int i = 0; i < recDataLength; i++)
{
listRecData.Add(receiveBytes[i]);
}
switch (UTTrans.analysisRecData(ref listRecData, ref rec_realDataLength, ref rec_frameNumber, ref rec_frameEquCount, ref rec_sourceStationId, ref rec_sourceStationType))
{
case UT_Center.RecOperation.OK:
MessageBox.Show("OK");
break;
case UT_Center.RecOperation.ERROR_REC_Length:
MessageBox.Show("网络异常——数据长度错误");
break;
case UT_Center.RecOperation.recReplyFrame:
MessageBox.Show("应答帧");
break;
case RecOperation.recAccordFrame:
MessageBox.Show("主动发送帧");
break;
case RecOperation.recACKFrame:
MessageBox.Show("ACK、NAK帧");
break;
case RecOperation.ERROR_REC_CHECK:
MessageBox.Show("网络异常——校验错误,数据不正确");
break;
}
rec_sourceStationId = 0;
rec_sourceStationType = 0;
rec_realDataLength = 0;
rec_frameNumber = 0;
rec_frameEquCount = 0;
listRecData.Clear();
//恢复挂起的心跳检测线程
if (thredSendHeart.ThreadState == ThreadState.Suspended)
{
thredSendHeart.Resume();
}
#region 发送数据
private void sendData(ArrayList data,int len)
{
byte[] sendData = new byte[len];
int i = 0;
foreach (byte itm in data)
{
sendData[i] = itm;
i++;
}
IPEndPoint targetiep = new IPEndPoint(IPAddress.Parse(targetIp), portId);
EndPoint temp = (EndPoint)targetiep;
int retry = 0;
while (tcpConnect)
{
try
{
stRead.SendTo(sendData, temp);
break;
}
catch
{
if (retry < 3)
{
retry++;
continue;
}
else
{
MessageBox.Show("发送失败!");
break;
}
}
}
sendData = null;
data.Clear();
len = 0;
}
#endregion