2015-01-30 7 views
0

소켓 프로그래밍에서 간단한 응용 프로그램을 만듭니다. 나는 이것이 이것을 달성하는 간단한 방법이라고 생각한다. 그래서 이것이 내가 이것을 나눠주고있는 이유입니다. 이 프로그램에서는 서버 프로그램 및 클라이언트 프로그램을 만들 수 있습니다. 또한 클라이언트와 서버에서 메시지를주고받을 수 있습니다. 여기 내 코드간단한 프로그래밍 예제 C가 날카로운

서버 프로그램입니다 : -

class Program 
    { 
     private const int port = 4532; 
     static void Main(string[] args) 
     {      

      IPEndPoint ip = new IPEndPoint(IPAddress.Any, 4532); 
      Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); 

      socket.Bind(ip); 
      socket.Listen(10); 
      Console.WriteLine("Waiting for client"); 
      Socket client = socket.Accept(); 
      IPEndPoint clientIP = (IPEndPoint)client.RemoteEndPoint; 
      Console.WriteLine(" >> Connected with" + clientIP.Address + "at port" + clientIP.Port); 
      Console.WriteLine(" >> Accept connection from client"); 

      string welcome = "Welcome"; 
      byte[] data = new byte[1024]; 
      data = Encoding.ASCII.GetBytes(welcome); 
      client.Send(data, data.Length, SocketFlags.None); 
      Console.WriteLine("......"); 
      Console.Read(); 

     } 

    } 

클라이언트 프로그램 : -

class Program 
    { 
     static void Main(string[] args) 
     { 

      Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); 
      IPEndPoint ip = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 4532); 
      Console.WriteLine("Client Started"); 
      try 
      { 
       socket.Connect(ip); 
      } 
      catch(SocketException e) 
      { 
       Console.WriteLine("Enable to connect"); 
      } 
      Console.WriteLine("Conneted to server"); 

      byte[] data = new byte[1024]; 
      int receivedata = socket.Receive(data); 
      string stringdata = Encoding.ASCII.GetString(data, 0, receivedata); 
      Console.WriteLine(stringdata); 
      Console.Read(); 
     } 
    } 

답변

1

글쎄, 그것은 전적으로 옳지 않다.

Encoding.ASCII.GetBytes은 매번 새로운 배열을 제공하므로 new byte[1024] 초기화가 쓸모 없으며 문자열이 클 경우 배열이 더 클 수 있습니다.

서버가 1024 이상의 페이로드를 보내는 경우 어떻게됩니까? 클라이언트는 메시지를 자르므로 XML 또는 JSON과 같은 구조화 된 데이터 형식을 사용하는 경우 직렬화 오류가 발생합니다. TCP 통신에서 메시지를 시작하거나 끝낼 때 코드가 결정할 수있는 방식으로 데이터를 프레이밍하는 프로토콜을 정의해야합니다. 예를 들어, 줄당 메시지 또는 WebSocket 프레이밍과 같이 더 복잡한 메시지를 결정할 수 있습니다.

서버가 하나의 클라이언트 만 허용하고 환영 메시지를 보내고 Console.Read에 걸릴 수 있습니다. 루프에서 더 많은 클라이언트를 청취하고 연결된 클라이언트마다 새 스레드를 시작하거나 비동기 작업을 사용해야합니다. 클라이언트와 동일하게 루프에서 메시지를 수신해야합니다.

예를 더 확장하려면 async/await를 고려하십시오. 프로덕션 준비가 된 TCP 서버는 적절하게 확장하기 위해 멀티 스레딩해야합니다.

생산 준비가 아닌 asynchronous TCP server and client의이 예제를 살펴보면 버퍼 읽기 및 비동기 작업과 관련된 개념 증명을하기에 충분합니다.