我在C#中编写了一个简单的Tcp服务器: (当它与服务器没有任何关系时,我已经替换了“做一些东西”中的一些代码部分。 现在,当我尝试从python客户端或Android客户端联系服务器时,我收到错误,例如:“另一方主动拒绝连接”。我应该做些什么?是我的C#代码中的问题,还是我可能没有正确联系它? 谢谢。
public bool ListenLoop(Int32 port, IPAddress localAddr)
{
try
{
server = new TcpListener(localAddr, port);
// Start listening for client requests.
server.Start();
// Buffer for reading data
Byte[] bytes = new Byte[256];
String data = null;
// Enter the listening loop.
while(true)
{
//Waiting for a connection
// Perform a blocking call to accept requests.
TcpClient client = server.AcceptTcpClient();
//connected!
// Get a stream object for reading and writing
NetworkStream stream = client.GetStream();
int i;
// Loop to receive all the data sent by the client.
while((i = stream.Read(bytes, 0, bytes.Length))!=0)
{
// Translate data bytes to a ASCII string.
data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
//handling opCodes
if(data[0] == '0') //log in
{
//do some stuff
byte[] msg = System.Text.Encoding.ASCII.GetBytes(response);
// Send back a response.
stream.Write(msg, 0, msg.Length);
//sent
}
else if (data[0] == '1') //download tune names
{
//do some stuff
byte[] msg = System.Text.Encoding.ASCII.GetBytes(response); //response is the names
// Send back a response.
stream.Write(msg, 0, msg.Length);
//sent
}
else if (data[0] == '2') //changing choice
{
//do some stuff
byte[] msg = System.Text.Encoding.ASCII.GetBytes(response);
// Send back a response.
stream.Write(msg, 0, msg.Length);
//sent
}
}
// Shutdown and end connection
client.Close();
}
}
catch(SocketException)
{
return false;
}
finally
{
// Stop listening for new clients.
server.Stop();
}
}
答案 0 :(得分:0)
您确定没有阻止传入连接的防火墙(因为它是TCP)吗?
此外,如果您的服务器正在测试中,您应该将一些输出写入日志文件,甚至只是控制台。至少你知道发生了什么。
答案 1 :(得分:0)
server = new TcpListener(localAddr,port); 改成 server = new TcpListener(port);