【发布时间】:2015-11-27 22:42:31
【问题描述】:
以下代码是 Microsoft 的 TcpListener 代码示例,但我无法运行:
using System;
using System.Net;
using System.Net.Sockets;
public class TcpListenerSample
{
static void Main(string[] args)
{
try
{
// set the TcpListener on port 13000
int port = 13000;
TcpListener server = new TcpListener(IPAddress.Any, port);
// Start listening for client requests
server.Start();
// Buffer for reading data
byte[] bytes = new byte[1024];
string data;
//Enter the listening loop
while (true)
{
Console.Write("Waiting for a connection... ");
// Perform a blocking call to accept requests.
// You could also user server.AcceptSocket() here.
TcpClient client = server.AcceptTcpClient();
Console.WriteLine("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.
i = stream.Read(bytes, 0, bytes.Length);
while (i != 0)
{
// Translate data bytes to a ASCII string.
data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
Console.WriteLine(String.Format("Received: {0}", data));
// Process the data sent by the client.
data = data.ToUpper();
byte[] msg = System.Text.Encoding.ASCII.GetBytes(data);
// Send back a response.
stream.Write(msg, 0, msg.Length);
Console.WriteLine(String.Format("Sent: {0}", data));
i = stream.Read(bytes, 0, bytes.Length);
}
// Shutdown and end connection
client.Close();
}
}
catch (SocketException e)
{
Console.WriteLine("SocketException: {0}", e);
}
Console.WriteLine("Hit enter to continue...");
Console.Read();
}
}
代码留在这一行的循环中:
TcpClient client = server.AcceptTcpClient();
我已关闭防火墙,但没有任何改变。
我该如何解决这个问题?
【问题讨论】:
-
您是否尝试连接到此服务器?
-
你可以看看这个问题,也许这可以帮助你找到你的问题:stackoverflow.com/a/19476156/2865804
-
它应该“停留”在该行,直到您连接到端口 13000。您可以通过启动命令提示符并在同一位置发出 telnet 127.0.0.1 13000 来轻松尝试它“停留”在那里机器。 (您应该安装了 telnet 客户端。如何安装它超出了范围)。然后它应该继续下一行。