TCP服务器
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using _0709_综合项目.FormAll;
using HalconDotNet;
namespace _0709_综合项目
{
public class tcpServer
{
#region 通讯
Socket _Seriver;
public static Socket ClientSocket;
Thread rec;
Thread th;
public static bool isSend;
public static string strSend;
bool isOpen = false;
byte[] buffer = new byte[1024 * 1024];
public void StarSer(string tb_IP,string tb_Port)
{
if (!isOpen)
{
IPAddress IP = IPAddress.Parse(tb_IP);
_Seriver = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
_Seriver.Bind(new IPEndPoint(IP, int.Parse(tb_Port)));
_Seriver.Listen(10);
th = new Thread(new ThreadStart(ListenThread));
th.IsBackground = true;
th.Start();
isOpen = true;
}
else
{
if (_Seriver != null)
{
_Seriver.Close();
}
if (ClientSocket != null)
{
ClientSocket.Close();
}
isOpen = false;
}
}
public void ListenThread()
{
try
{
while (true)
{
ClientSocket = _Seriver.Accept();
isSend = true;
strSend = "连接成功!";
rec = new Thread(new ParameterizedThreadStart(RecDataThread));
rec.IsBackground = true;
rec.Start(ClientSocket);
}
}
catch (Exception) { }
}
public void RecDataThread(object obj)
{
try
{
Socket _socketClient = (Socket)obj;
while (true)
{
int counts = _socketClient.Receive(buffer);
if (counts > 0)
{
string str = Encoding.Default.GetString(buffer, 0, counts);
isSend = true;
strSend = str;
if (str.Substring(0, 2) == "OK")
{
Position.MRE.Set();
Fit.MRE1.Set();
Fit.MRE2.Set();
Fit.MRE3.Set();
MoveCam.MREMove.Set();
Calibration.MREcalib.Set();
Correction.MREDown.Set();
}
}
}
}
catch (Exception) { }
}
public void sendData(string str )
{
byte[] buffer = Encoding.Default.GetBytes(str);
ClientSocket.Send(buffer);
}
#endregion
}
}
|