3

1つのソケットで双方向接続を行う適切な方法が(C#)であることを知りたいだけです。

client-pc / routerのポートを開かずに、クライアントがサーバーからデータを送信および受信する必要があります。

サーバーはマルチプレイヤー ゲーム サーバーであり、クライアントはゲームをプレイするためにポートを余分に開いてはいけません。

単純なソケット接続は 2 つの方法で機能しますか (サーバーにはソケット リスナーがあり、クライアントはサーバー ソケットに接続します)。

そのテキストが私の質問をほとんど説明していることを願っています。

4

2 に答える 2

6

はい、クライアントはポートにのみ接続できます。その後、サーバーはクライアントの接続に応答する場合があります

クライアントサーバーリクエストとそのレスポンス

クライアント

IPEndPoint ip = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9999);

  Socket server = new Socket(AddressFamily.InterNetwork,SocketType.Stream, ProtocolType.Tcp);

  try
  {
     server.Connect(ip); //Connect to the server
  } catch (SocketException e){
     Console.WriteLine("Unable to connect to server.");
     return;
  }

  Console.WriteLine("Type 'exit' to exit.");
  while(true)
  {
     string input = Console.ReadLine();
     if (input == "exit")
        break;
     server.Send(Encoding.ASCII.GetBytes(input)); //Encode from user's input, send the data
     byte[] data = new byte[1024];
     int receivedDataLength = server.Receive(data); //Wait for the data
     string stringData = Encoding.ASCII.GetString(data, 0, receivedDataLength); //Decode the data received
     Console.WriteLine(stringData); //Write the data on the screen
  }

  server.Shutdown(SocketShutdown.Both);
  server.Close();

これにより、クライアントはサーバーにデータを送信できます。次に、サーバーからの応答を待ちます。ただし、サーバーが応答しない場合、クライアントは長時間ハングアップします。

これはサーバーからの例です

IPEndPoint ip = new IPEndPoint(IPAddress.Any,9999); //Any IPAddress that connects to the server on any port
  Socket socket = new Socket(AddressFamily.InterNetwork,SocketType.Stream, ProtocolType.Tcp); //Initialize a new Socket

  socket.Bind(ip); //Bind to the client's IP
  socket.Listen(10); //Listen for maximum 10 connections
  Console.WriteLine("Waiting for a client...");
  Socket client = socket.Accept();
  IPEndPoint clientep =(IPEndPoint)client.RemoteEndPoint;
  Console.WriteLine("Connected with {0} at port {1}",clientep.Address, clientep.Port);

  string welcome = "Welcome"; //This is the data we we'll respond with
  byte[] data = new byte[1024];
  data = Encoding.ASCII.GetBytes(welcome); //Encode the data
  client.Send(data, data.Length,SocketFlags.None); //Send the data to the client
  Console.WriteLine("Disconnected from {0}",clientep.Address);
  client.Close(); //Close Client
  socket.Close(); //Close socket

これにより、サーバーはクライアントの接続時にクライアントに応答を返すことができます。

ありがとう、
これがお役に立てば幸いです:)

于 2012-10-29T13:04:33.150 に答える
1

単純なソケット接続は全二重接続です。つまり、単一のソケットを使用して双方向通信が可能です。

完全な例を次に示します。

于 2012-10-29T12:29:59.983 に答える