-2

私は初心者の学生ソケット プログラミングです。「TCP/IP Sockets in C# Practical Guide for Programmers」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:通常、各ソケット アドレスの 1 つの使用のみが許可されます

そしてプログラム終了。何をすべきか?

4

2 に答える 2

2

で指定したポートnew TcpListener(IPAddress.Any, servPort);は使用中のようですが、許可されていません (特定のポートでリッスンできるプログラムは 1 つだけです)。

これは、サーバー プログラムの複数のインスタンスが実行されているか、別のプログラムによって使用されていることが原因である可能性があります。たとえば、マシンで Web サーバーを実行している場合、通常はポート 80 が使用されます。

別のポート番号 (例: 10000) を選択してみてください。よく知られたプログラム (Web サーバー、メール サーバーなど - 詳細については、このウィキペディアのページを参照してください)で使用されるため、小さいポート番号 (特に 1024 未満) は避けます。

于 2011-10-31T16:25:07.090 に答える
1

Visual Studio 2010 を使用してこれを (デバッグ経由で) コンパイルおよび実行した場合は、コードで必要なコマンド ライン引数を設定する必要があります。

コマンド ライン引数を使用して (コンソールまたは VS で設定して) 既にプログラムを実行している場合は、それが機能しない理由をより詳細に説明してください。

コマンド ライン引数を設定するには、ソリューション エクスプローラー -> [プロパティ] でプロジェクトを右クリックし、[デバッグ] タブで、[コマンド ライン引数] フィールドにポートを表す値を入力します。スペースはなく、値は 1 つだけです。

于 2011-10-31T16:10:42.230 に答える