c#中的TCP服务器
本文关键字:服务器 TCP 中的 | 更新日期: 2023-09-27 18:12:58
我只是一个初学者。我尝试了一个简单的代码从"TCP/IP套接字在c#程序员实用指南"pdf书,但它不工作。我在visual studio 2010中编译了它。请告诉我有什么问题,这里是完整的代码
using System; // For Console, Int32, ArgumentException, Environment
using System.Net; // For IPAddress
using System.Net.Sockets; // For TcpListener, TcpClient
class TcpEchoServer {
private const int BUFSIZE = 32; // Size of receive buffer
static void Main(string[] args) {
if (args.Length > 1) // Test for correct # of args
throw new ArgumentException("Parameters: [<Port>]");
int servPort = (args.Length == 1) ? Int32.Parse(args[0]): 7;
TcpListener listener = null;
try {
// Create a TCPListener to accept client connections
listener = new TcpListener(IPAddress.Any, servPort);
listener.Start();
} catch (SocketException se) {
Console.WriteLine(se.ErrorCode + ": " + se.Message);
Environment.Exit(se.ErrorCode);
}
byte[] rcvBuffer = new byte[BUFSIZE]; // Receive buffer
int bytesRcvd; // Received byte count
for (;;) { // Run forever, accepting and servicing connections
TcpClient client = null;
NetworkStream netStream = null;
try {
client = listener.AcceptTcpClient(); // Get client connection
netStream = client.GetStream();
Console.Write("Handling client - ");
// Receive until client closes connection, indicated by 0 return value
int totalBytesEchoed = 0;
while ((bytesRcvd = netStream.Read(rcvBuffer, 0, rcvBuffer.Length)) > 0) {
netStream.Write(rcvBuffer, 0, bytesRcvd);
totalBytesEchoed += bytesRcvd;
}
Console.WriteLine("echoed {0} bytes.", totalBytesEchoed);
// Close the stream and socket. We are done with this client!
netStream.Close();
client.Close();
} catch (Exception e) {
Console.WriteLine(e.Message);
netStream.Close();
}
}
}
}
从评论:
我有客户端程序也连接到这个服务器程序。实际的问题是这个服务器程序没有运行。在第16-22行,代码try
{ // Create a TCPListener to accept client connections
listener = new TcpListener(IPAddress.Any, servPort);
listener.Start();
}
catch (SocketException se)
{
Console.WriteLine(se.ErrorCode + ": " + se.Message);
Environment.Exit(se.ErrorCode);
}
和程序显示错误代码并显示如下信息
10048:每个套接字地址通常只允许使用一次
和程序关闭。该怎么办?
您在new TcpListener(IPAddress.Any, servPort);
中指定的端口似乎正在使用中,这是不允许的(只有一个程序可以侦听特定的端口)
这可能是因为您的服务器程序有多个实例正在运行,也可能是因为它被另一个程序使用。例如,如果您的机器上运行web服务器,则通常使用80端口。
尝试选择另一个端口号(例如10000)。我会避免较低的端口号(特别是低于1024),因为这些是由众所周知的程序(web服务器,邮件服务器等-请参阅此维基百科页面了解更多信息)
如果你使用Visual Studio 2010来编译和运行这个(通过Debug),你应该设置命令行参数,因为你的代码需要它们。
如果你已经用命令行参数运行了你的程序(无论是通过控制台还是在VS中设置),那么请给出一个更详细的解释为什么它不能工作。
要设置命令行参数,请在"解决方案资源管理器->属性"中右键单击项目,然后在"调试"选项卡中,在"命令行参数"字段中键入表示端口的值。没有空格,只有一个值