本文介绍了C#套接字编程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
你好我有一个代码:
Hello i have a code:
public class Network
{
public Socket read;
public IPEndPoint ie;
public Network(string ip)
{
read = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
ie = new IPEndPoint(IPAddress.Parse(File.ReadAllText("c:\\ipaddress.txt")), 502);
}
public bool InitConnection()
{
read.Connect(ie);
return read.Connected;
}
public int send(byte[] data)
{
return read.Send(data);
}
public byte[] receive()
{
byte[] data = new byte[41];
int num = read.Receive(data);
return data;
}
public void close_connection()
{
//read.Close();
read.Shutdown(SocketShutdown.Both);
}
public void refreshSocket()
{
read.Shutdown(SocketShutdown.Both);
}
}
- 上面的类用于与设备建立套接字连接。
- 在主要类中:
SCENARIO1:
- The above class is used to establish socket connection with a device.
- In the main class:
SCENARIO1:
static void main()
{
byte[] data = new data[]{0x01,0x02,0x44,0x34,0x23,0x11};
Networking net = new Networking();
if(net.InitConnection())
{
net.send(data);
net.receive();
}
////Please note that i have used all the data from the Networking class, while doing so i am receiving correct data in the receiving buffer. In short every thing works fine.
}
SCENARIO2:
SCENARIO2:
static void main()
{
byte[] data = new data[]{0x01,0x02,0x44,0x34,0x23,0x11};
byte[] ret = new ret[41];
Socket read = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
read.Connect("172.16.3.230", 502);
read.Send(data);
read.Receive(ret);
////please note here i am explicitly sending the data over the socket i.e directly connecting not through any class. But this time i get an Error. If i do the below thing :
foreach(byte b in ret)
Console.WriteLine(b.ToString("x2"));
///Here the result shows that the data which i receive into the ret buffer is shifted by one position to the right.
///for example if received data is : 01 02 03 04, then after shifting: 00 01 02 03.
/// I have lost the last byte.
/// I am communicating with a PLC device and reading its holding registers. This problem doesnt occur if i read the coils of the PLC device.
}
谢谢,
- Rahul
Thanks,
- Rahul
推荐答案
这篇关于C#套接字编程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!