2012-10-29 3 views
2

한 소켓으로 양방향 연결을 수행하는 적절한 방법이 (C#)인지 알고 싶습니다.멀티 클라이언트 서버 - 양방향 연결을위한 일반적인 방법

client-pc/router에서 포트를 열지 않고 서버에서 데이터를 보내고 데이터를 수신해야합니다.

서버는 멀티 플레이어 게임 서버이며 클라이언트는 게임을 실행하기 위해 포트를 추가로 열어서는 안됩니다.

두 가지 방법으로 간단한 소켓 연결이 작동합니까 (서버에 소켓 수신기가 있고 클라이언트가 서버 소켓에 연결)?

텍스트가 내 질문을 거의 설명하기를 바랍니다.

답변

6

예, 클라이언트는 포트에만 연결할 수 있습니다. 그런 다음, 서버는이 클라이언트가 서버에 데이터를 보낼 수 있도록 클라이언트의 연결

Client-Server Request and its response

클라이언트

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 

서버에서 예입니다.

감사합니다,
난 당신이 클라이언트가 포트를 열 필요가 없습니다이 도움이 :)

+0

알았어요. 하지만 클라이언트가 응답하지 않고 서버가 데이터를 전송해야한다면 어떻게 될까요? – Ace

+0

의미 : 하나의 클라이언트가 "안녕 모두"를 입력하므로 서버가 thsi 메시지를 가져 와서 다른 모든 클라이언트에게 보냅니다. 그러나 한 클라이언트가 아무 것도 입력하지 않으면 응답을 기다리지 않습니다. 알고 계십니까? 내 말은 ? – Ace

+0

@Ace 예. 서버는 클라이언트가 보낸 데이터가있는 경우에만 응답 할 수 있습니다. 또한 클라이언트가 연결된 후에 클라이언트에 응답 할 수있는 기회가 있습니다. –

1

간단한 소켓 연결은 전이중 연결입니다. 예, 단일 소켓을 사용하여 양방향 통신이 가능합니다.

Here's a complete example.

+0

그래서 방법을 찾아 희망? 그래서 서버가 열어야합니까? – Ace

+0

예. 그게 소켓이 작동하는 방법입니다 :) – darth10

관련 문제