2012-10-22 4 views
0

비동기 클라이언트 - 서버 소켓을 사용하는 MSDN 예제 코드를 연구 중입니다. 클라이언트의 새로운 연결이 만들어 질 때 이것이 어떻게되는지 이해합니다.비동기 클라이언트 소켓 : 서버에 추가 데이터를 전달하는 방법은 무엇입니까?

그러나 클라이언트가 이미 연결되어 있고 서버 (또는 다른 클라이언트)에 새로운 데이터를 전달하려는 경우 어떻게해야합니까?

내가 지금까지 무엇을 가지고 :

public partial class Form1 : Form 
{ 
    AsynchronousClient ac; 
    public Form1() 
    { 
     InitializeComponent();    
    } 

    private void buttonLogin_Click(object sender, EventArgs e) 
    { 
     buttonLogin.Enabled = false; 
     new Thread(new ThreadStart(CreatingConnection)).Start(); 
    } 

    private void CreatingConnection() 
    { 
     ac = new AsynchronousClient(); 
     ac.SendingMessage += (msg) => AC_SendingMassage(msg); 
     ac.StartClient(); 
    } 

    private void AC_SendingMassage(string message) 
    { 
     listBox1.Invoke((MethodInvoker)delegate { listBox1.Items.Add(message); }); 
    } 

    private void buttonData_Click(object sender, EventArgs e) 
    { 
     string message = textBox1.Text; 
     //TODO: 
     //how to send data from here (including whats in textBox)?? 
    } 
} 

그리고이 msdn`s 예제 코드 (2 등급)입니다 (전용 클라이언트 incluidng) :

public class StateObject 
{ 
    public Socket workSocket = null; 
    public const int BufferSize = 256; 
    public byte[] buffer = new byte[BufferSize]; 
    public StringBuilder sb = new StringBuilder(); 
} 

public class AsynchronousClient 
{ 
    public event Action<string> SendingMessage; 
    // The port number for the remote device. 
    private const int port = 11000; 

    // ManualResetEvent instances signal completion. 
    private static ManualResetEvent connectDone = new ManualResetEvent(false); 
    private static ManualResetEvent sendDone = new ManualResetEvent(false); 
    private static ManualResetEvent receiveDone = new ManualResetEvent(false); 

    // The response from the remote device. 
    private string response; 

    public void StartClient() 
    { 
     // Connect to a remote device. 
     try 
     { 
      // Establish the remote endpoint for the socket. 
      string ip = "192.168.1.101"; 
      IPAddress ipAddress = IPAddress.Parse(ip); 
      IPEndPoint remoteEP = new IPEndPoint(ipAddress, port); 

      // Create a TCP/IP socket. 
      Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); 

      // Connect to the remote endpoint. 
      client.BeginConnect(remoteEP, new AsyncCallback(ConnectCallback), client); 
      connectDone.WaitOne(); 

      // Send test data to the remote device. 
      Send(client, "This is a test<EOF>"); 
      sendDone.WaitOne(); 

      // Receive the response from the remote device. 
      Receive(client); 
      receiveDone.WaitOne(); 

      // Write the response to the console. 
      SendingMessage(string.Format("Response received : {0}", response)); 

      // Release the socket. 
      client.Shutdown(SocketShutdown.Both); 
      client.Close(); 
     } 
     catch (Exception e) 
     { 
      SendingMessage(e.Message); 
     } 
    } 

    private void ConnectCallback(IAsyncResult ar) 
    { 
     try 
     { 
      // Retrieve the socket from the state object. 
      Socket client = (Socket)ar.AsyncState; 

      // Complete the connection. 
      client.EndConnect(ar); 

      //Console.WriteLine("Socket connected to {0}", client.RemoteEndPoint.ToString()); 
      SendingMessage(string.Format("Socket connected to {0}", client.RemoteEndPoint.ToString())); 

      // Signal that the connection has been made. 
      connectDone.Set(); 
     } 
     catch (Exception e) 
     { 
      //Console.WriteLine(e.ToString()); 
      SendingMessage(e.Message); 
     } 
    } 

    private void Receive(Socket client) 
    { 
     try 
     { 
      // Create the state object. 
      StateObject state = new StateObject(); 
      state.workSocket = client; 

      // Begin receiving the data from the remote device. 
      client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReceiveCallback), state); 
     } 
     catch (Exception e) 
     { 
      SendingMessage(e.Message); 
     } 
    } 

    private void ReceiveCallback(IAsyncResult ar) 
    { 
     try 
     { 
      // Retrieve the state object and the client socket from the asynchronous state object. 
      StateObject state = (StateObject)ar.AsyncState; 
      Socket client = state.workSocket; 

      // Read data from the remote device. 
      int bytesRead = client.EndReceive(ar); 

      if (bytesRead > 0) 
      { 
       // There might be more data, so store the data received so far. 
       state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, bytesRead)); 

       // Get the rest of the data. 
       client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReceiveCallback), state); 
      } 
      else 
      { 
       // All the data has arrived; put it in response. 
       if (state.sb.Length > 1) 
       { 
        response = state.sb.ToString(); 
       } 
       // Signal that all bytes have been received. 
       receiveDone.Set(); 
      } 
     } 
     catch (Exception e) 
     { 
      SendingMessage(e.Message); 
     } 
    } 

    public void Send(Socket client, string data) 
    { 
     // Convert the string data to byte data using ASCII encoding. 
     byte[] byteData = Encoding.ASCII.GetBytes(data); 

     // Begin sending the data to the remote device. 
     client.BeginSend(byteData, 0, byteData.Length, 0, new AsyncCallback(SendCallback), client); 
    } 

    private void SendCallback(IAsyncResult ar) 
    { 
     try 
     { 
      // Retrieve the socket from the state object. 
      Socket client = (Socket)ar.AsyncState; 

      // Complete sending the data to the remote device. 
      int bytesSent = client.EndSend(ar); 
      //Console.WriteLine("Sent {0} bytes to server.", bytesSent); 
      SendingMessage(string.Format("Sent {0} bytes to server.", bytesSent)); 
      // Signal that all bytes have been sent. 
      sendDone.Set(); 
     } 
     catch (Exception e) 
     { 
      SendingMessage(e.Message); 
     } 
    } 
} 

- 위로 buttonData의 click 이벤트가 있는데,이 이벤트는 서버에 데이터를 전달하는 데 사용하고 싶습니다. 이미 연결된 경우 새 데이터를 전달하기 위해 호출 할 메소드를 알고 싶습니다.

답변

0

Send 방법을 사용하여 데이터를 보냅니다. 그러나이 샘플 코드는 실제로 이러한 비동기 메서드 중 일부가 작동하는 방식을 보여주기위한 것일뿐입니다. StartClient 메서드는 모든 것을 종료합니다. 이는 아마도 사용자가 원하는 것이 아닙니다. 이렇게하려면 자신 만의 코드를 작성해야 할 것입니다.

관련 문제