C# Socket程序结构分析及应用
简易的机器人和PLC信息提取。
----Socket程序结构分析: ---------
privateSocket server; 声明 Socket类提供一组丰富的网络通信方法和属性.
privateSocket client;
public void OpenTCP() ----建立程序
{
myThreadDelegate = new ThreadStart(Listen);
委托属性的变量激活委托指令启动线程监听
myThread = new Thread(myThreadDelegate);初始化线程类型变量
myThread.Start();线程类型变量开始执行
}
///
/// 创建TCP服务端并监听
///
public void Listen()//创建tcp服务端
{
//设置IP
string IP = ipAddressTB.Text;
int Port = Convert.ToInt32(portTB.Text); 设置端口
//初始化终结点实例
//初始化SOCKET实例
server = new Socket(localEP.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
server.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
ShowMsg("等待客户端连接..."); 发出信息
try
{
//绑定
server.Bind(localEP);
//监听10次
server.Listen(10);
client = server.Accept(); 服务接收
IPEndPoint clientIP = (IPEndPoint)client.RemoteEndPoint;
ShowMsg("已连接的客户端:" + clientIP.Address + ",端口:" + clientIP.Port);
Received_Robot();从机器人接收信息
}
catch (Exception ex)
{
//MessageBox.Show(ex.Message, "Listen_Error");
}
}
IPEndPoint(IPAddress.Parse(IP), Port)
重载 |
|
IPEndPoint(Int64, Int32) |
|
IPEndPoint(IPAddress, Int32) |
Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
InterNetwork |
2 |
Tcp |
6 |
传输控制协议。 |
---------------------------------------END--------------------------
每天进步一点点
Make small but daily progress