我的软件由两部分组成。其中一个是客户端,我可以通过以太网在路由器上连接我的设备,我可以发送命令(数据)然后我开始等待从我的设备得到响应,但我无法弄清楚我怎么能得到响应,尽管事实上,我一直在寻找类似的套接字应用程序。我已经学习了2年的c#。你能帮我解决一下这个话题吗?
如果你能帮助我,我会非常高兴你。
namespace sencron_socket
{
class Program
{
static Socket sck;
static Socket scks;
static byte[] Buffer { get; set; }
static void Main(string[] args)
{
sck = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint localendpoint = new IPEndPoint(IPAddress.Parse("172.16.204.101"), 50007); //50007 bidirectional interface The event
try
{
sck.Connect(localendpoint);
if (sck.Poll(-1, SelectMode.SelectWrite))
{
Console.WriteLine("this socket is writable");
}
else if (sck.Poll(-1, SelectMode.SelectError))
{
Console.WriteLine("this socket has an error");
}
}
catch
{
Console.Write(" unable ");
Main(args);
}
Console.Write("enter text: ");
string text = Console.ReadLine();
byte[] data = Encoding.ASCII.GetBytes(text);
sck.Send(data);
Console.Write(" data sent! \r\n ");
//Console.Write(" press ant key to continue ");
// Console.Read();
sck.Close();
scks = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
scks.Bind(new IPEndPoint(IPAddress.Parse("172.16.204.104"),0));
scks.Listen(1);
Console.Write(" it is ok until this step ");
// ???????????????????????????????????????????????????????
// i think that my problem starts next line with Accept()
Socket accepted = scks.Accept();
Console.Write(" BURDA 222 \r\n");
IPEndPoint remoteEndPoint = (IPEndPoint)accepted.RemoteEndPoint;
Buffer = new byte[accepted.SendBufferSize];
int bytesRead = accepted.Receive(Buffer);
byte[] formatted = new byte[bytesRead];
/* for (int i = 0; i < bytesRead; i++)
{
formatted[i] = Buffer[i];
}*/
Console.Write(" BURDA 3333 ");
string strData = Encoding.ASCII.GetString(formatted);
Console.Write(strData + "\r\n");
scks.Close();
accepted.Close();
Console.Read();
}
}
}