2016-12-20 8 views
-1

クライアントにデータを送信するためにサーバーに送信ボタンを追加しようとしていますが、接続が正常に動作しています。ボタンの下にコードを追加しようとしました_click私はこのメッセージを受け取ります: ソケットが接続されていないため、データの送受信を要求できませんでした。ここで サーバー側のコード」サーバーのボタンを送信側が動作していないTCP C#

public partial class Server : Form 
{ 
    public Server() 
    { 
     InitializeComponent(); 

     ListBox.CheckForIllegalCrossThreadCalls = false; 
     // call server connection method 
     connection(); 
    } 


    private Socket _server; 
    Socket _client; 
    private byte [] _buffer = new byte[1024]; 
    private Socket client; 
    Socket oldConnection; 


    /** 
    * Server Connection Binding and listening method 
    */ 
    private void connection() 
    { 
     _server = new Socket(AddressFamily.InterNetwork, 
      SocketType.Stream, ProtocolType.Tcp); 
     try 
     { 
      _server.Bind(new IPEndPoint(IPAddress.Any, 5020)); 
      _server.Listen(5); 
      // before connecting to any client 
      status.Items.Add("Waiting for client..."); 

      _server.BeginAccept(new AsyncCallback(AcceptConn), _server); 
     } 
     catch(Exception ex) 
     { 
      MessageBox.Show(ex.Message); 
     } 
    } 

    // Accept Clients Connections 
    private void AcceptConn(IAsyncResult iar) 
    { 
     try 
     { 
      oldConnection = (Socket)iar.AsyncState; 
      client = (Socket)oldConnection.EndAccept(iar); 
      // if the socket status is connected 
      // add 
      // Connected to: clientIP:Portnumber 
      status.Items.Add("Connected to: " + client.RemoteEndPoint.ToString()); 
      // welcom message from server 
      string welcome = "Welcome to my server"; 
      byte[] welcomeMessage = Encoding.ASCII.GetBytes(welcome); 

      client.BeginSend(welcomeMessage, 0, welcomeMessage.Length, 
       SocketFlags.None, new AsyncCallback(SendData), client); 

      // Accept next client Connection 
      oldConnection.BeginAccept(new AsyncCallback(AcceptConn),oldConnection); 
     } 
     catch(Exception ex) 
     { 
      MessageBox.Show(ex.Message); 
     } 
    } 

    // create Send callback method to execute the BeginSend() call 
    private void SendData(IAsyncResult iar) 
    { 
     try 
     { 
      _client = (Socket)iar.AsyncState; 
      int sent = _client.EndSend(iar); 

      _client.BeginReceive(_buffer, 0, _buffer.Length, SocketFlags.None, 
       new AsyncCallback(ReceiveData), _client); 
     } 
     catch(Exception ex) 
     { 
      MessageBox.Show(ex.Message); 
     } 
    } 

    // create Receive callback method to execute the BeginReceive() call 
    private void ReceiveData(IAsyncResult iar) 
    { 
     try 
     { 
      Socket client = (Socket)iar.AsyncState; 
      int recv = client.EndReceive(iar); 

      if (recv == 0) 
      { 
       // updating status 
       status.Items.Add("Waiting for client..."); 
       // _server Socket will start Accepting new clients connections 
       _server.BeginAccept(new AsyncCallback(AcceptConn), _server); 
       return; 
      } 
      else 
      { 
       string receivedData = Encoding.ASCII.GetString(_buffer, 0, recv); 
       // add message to the ListBox 
       results.Items.Add(receivedData); 
       // resend client message to the client 
       byte[] message2 = Encoding.ASCII.GetBytes(receivedData); 

       client.BeginSend(message2, 0, message2.Length, SocketFlags.None, 
        new AsyncCallback(SendData), client); 
      } 
     } 
     catch(Exception ex) 
     { 
      MessageBox.Show(ex.Message); 
     } 
    } 

    private void Server_Load(object sender, EventArgs e) 
    { 

    } 

    private void button1_Click(object sender, EventArgs e) 
    { 
     try 
     { 
      byte[] strMessage = Encoding.ASCII.GetBytes("Server Sending .."); 
      client.BeginSend(strMessage, 0, strMessage.Length, SocketFlags.None, 
       new AsyncCallback(SendData), client); 
      MessageBox.Show("done"); 

     } 
     catch (Exception ex) 
     { 
      MessageBox.Show(ex.Message); 
     } 
    } 
} 
} 

に私は、非同期TCPのC#を使用しています。

+0

'client'と' _client'フィールドが少し混乱しています。目的のクライアントフィールドを使用していますか?使用しているものは明らかに接続されていないためです。 –

+0

私は両方を試してみましたが、あなたがコードを生きているように編集するのを見たらplsしました:( –

答えて

0

サーバーが複数のクライアントを受け入れるように設定されています。クライアントが承認されたらあなたは。受け入れるための別のソケットを持っている必要があります別のソケットオブジェクトにコピーしてList<socket>に追加して、次の接続に使用するソケットをリセットします。現在、次のクライアントを受け入れるようにリセットされたソケットにメッセージを送信しようとしています。あなたの接続されたソケットを保存し、受け取るための別のソケットを持っていれば、あなたのsendイベントはそのリストに格納されているソケットまたはそのすべてにメッセージを送ることができます。

var clients = new List<socket>(); 

.... 

private void AcceptConn(IAsyncResult iar) 
    { 
     try 
     { 
      oldConnection = (Socket)iar.AsyncState;    
      var clientSocket = (Socket)oldConnection.EndAccept(iar); 
      clients.Add(clientSocket); 
.... 
+0

ありがとう..しかし、私は非常に混乱していますので、現在の接続を保存するこの新しいソケットを書くことができます..クライアントか_clientでしょうか? –

+0

私は今も混乱している多くのソケットを持っています。あなたのケースでは、保存された接続はクライアントであるべきですが、新しい接続が受け入れられたときに常にクライアントが新しいインスタンスになるようにしてください。リスト。 – DonO

関連する問題