C# Socket 完整代码
时间: 2023-10-19 20:55:51 浏览: 93
Socket c#源码
5星 · 资源好评率100%
以下是一个简单的C# Socket通讯的示例代码:
```csharp
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
class Program
{
static void Main()
{
// 设定PLC的IP地址和端口号
string ipAddress = "192.168.0.1";
int port = 102;
try
{
// 创建一个Socket对象
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
// 连接到PLC
socket.Connect(IPAddress.Parse(ipAddress), port);
Console.WriteLine("Connected to PLC ...");
// 发送数据到PLC
string message = "Hello PLC!";
byte[] sendData = Encoding.ASCII.GetBytes(message);
socket.Send(sendData);
// 接收PLC的响应
byte[] buffer = new byte[1024];
int receivedBytes = socket.Receive(buffer);
string receivedData = Encoding.ASCII.GetString(buffer, 0, receivedBytes);
Console.WriteLine("Received data: " + receivedData);
// 关闭Socket连接
socket.Shutdown(SocketShutdown.Both);
socket.Close();
}
catch (Exception ex)
{
Console.WriteLine("Error: " + ex.Message);
}
Console.ReadLine();
}
}
```
这段代码通过创建一个Socket对象,使用指定的IP地址和端口号连接到PLC。然后,发送一条消息到PLC,并等待PLC的响应。最后,关闭Socket连接。需要根据实际情况修改IP地址和端口号,并根据PLC的通讯协议进行数据的发送和接收。
阅读全文