我想使用一个简单的套接字应用程序将字节数据从Python客户端发送到C#服务器。 C#服务器在C#客户端上运行良好!
但是当我尝试使用Python Socket将数据发送到C#-Server时,数据永远不会到达。
我不太习惯Python,有人可以检查我的代码并提示我如何在c#服务器中接收数据吗?
我在代码中犯了错误吗?这可能是从Python向C#发送字节数据的错误方法吗?有更好的解决方案吗?
Python客户端:
import socket
TCP_IP = '127.0.0.1'
TCP_PORT = 5005
MESSAGE = b'Hello World !'
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((TCP_IP, TCP_PORT))
s.send(MESSAGE)
s.close()
C#服务器:
private void start()
{
Console.WriteLine("Port: ");
_port = Console.ReadLine();
byte[] buffer = new Byte[1024];
IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), int.Parse(_port));
Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
listener.Bind(localEndPoint);
listener.Listen(10);
while (true)
{
Console.WriteLine("Waiting for a connection...");
Socket socket = listener.Accept();
data = null;
while (true)
{
int bytesRec = socket.Receive(buffer);
data += Encoding.ASCII.GetString(buffer, 0, bytesRec);
if (data.IndexOf("<EOF>") > -1)
{
break;
}
}
Console.WriteLine("Text received : {0}", data);
byte[] msg = Encoding.ASCII.GetBytes(data);
socket.Send(msg);
socket.Shutdown(SocketShutdown.Both);
socket.Close();
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
Console.WriteLine("\nPress ENTER to continue...");
Console.Read();
}