C# 中的 TCP 服务器
我只是一个初学者学生套接字编程。我尝试了“C# 程序员实用指南中的 TCP/IP 套接字”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:每个套接字地址通常只允许使用一次
并且程序关闭。该怎么办?
Iam just a beginner student socket programming.I tried a simple code from "TCP/IP Sockets in C# Practical Guide for Programmers" pdf book but it doesn't work.I compiled it in visual studio 2010.Please help me what is wrong and here is the complete code
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();
}
}
}
}
From Comment:
I have program for client also to connect with this server program. Actual problem is this server program does not run. At line 16-22 there is the code 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);
}
and program show the error code and displays message like this
10048:Only one usage of each socket address is normally permitted
and program close. What to do?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您在
new TcpListener(IPAddress.Any, servPort);
中指定的端口似乎正在使用,这是不允许的(只有一个程序可以侦听特定端口)。这可能是因为您的服务器程序有多个实例正在运行,或者因为它被另一个程序使用。例如,如果您的计算机上运行 Web 服务器,则通常会使用端口 80。
尝试选择另一个端口号(例如10000)。我会避免使用较低的端口号(尤其是低于 1024),因为这些端口号由众所周知的程序(Web 服务器、邮件服务器等)使用 - 请参阅 此维基百科页面了解更多信息)
The port you specify in
new TcpListener(IPAddress.Any, servPort);
seems to be in use, which is not permitted (only one program can listen on a specific port).This can be either because you have multiple instances of your server program running, or because it is used by another program. For example, port 80 is usually in use if you have a web server running on your machine.
Try to chose another port number (e.g. 10000). I would avoid lower port numbers (especially below 1024) since these are used by well known programs (web servers, mail servers, etc. - see this wikipedia page for more information)
如果您使用 Visual Studio 2010 编译并运行此程序(通过调试),则应根据代码需要设置命令行参数。
如果您已经使用命令行参数运行了您的程序(通过控制台或在 VS 中设置它们),那么请更详细地解释为什么它不起作用。
要设置命令行参数,请在解决方案资源管理器中右键单击您的项目 -> “属性”,然后在“调试”选项卡中的“命令行参数”字段中键入代表端口的值。没有空格,只有一个值。
If you used Visual Studio 2010 to compile and run this (via Debug), you should set up command line arguments as your code requires them.
If you already did run your program with command line arguments (either through console or by setting them up in VS), then please give a more detailed explanation of why it doesn't work.
To set up command line arguments, right click on your project in Solution Explorer -> Properties, then in Debug tab, type a value representing a port in the Command Line Arguments field. No spaces, only one value.