2012-05-03 15 views
4

私は多くを検索しましたが、インターネットのすべての例はコンソールアプリケーションです。私はWindowsフォームのコンソールアプリケーションの例を使用しようとしましたが、socket.startフォームをフリーズして状態を(応答ではなく)変更すると呼びます。また、私は複数のスレッドを試みたが、それはあまりにも失敗しました。可能であればアドバイスをお願いします。Windowsフォームアプリケーションを使用したC#ソケットサーバー

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Linq; 
using System.Text; 
using System.Windows.Forms; 
using System.Net; 
using System.Net.Sockets; 
using System.Threading; 

namespace mserver1 
{ 
    public partial class Form1 : Form 
    { 
     public Form1() 
     { 
      InitializeComponent(); 
     } 

     private void button1_Click(object sender, EventArgs e) 
     { 
      ServerClass sc = new ServerClass(); 
      sc.startServer(textBox1, richTextBox1); 
     } 
    } 


    public class ServerClass 
    { 
     public void startServer(TextBox tb, RichTextBox rb) 
     { 

      IPEndPoint ip = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9939); 
      Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); 

      socket.Bind(ip); 
      socket.Listen(20); 
      rb.Text = rb.Text + "Waiting for client..."; 
      Socket client = socket.Accept(); 
      IPEndPoint clientep = (IPEndPoint)client.RemoteEndPoint; 

      rb.Text = rb.Text + "Connected with " + clientep.Address + " at port " + clientep.Port; 

      string welcome = tb.Text; 
      byte[] data = new byte[1024]; 
      data = Encoding.ASCII.GetBytes(welcome); 
      client.Send(data, data.Length, SocketFlags.None); 

      rb.Text = rb.Text + "Disconnected from" + clientep.Address; 
      client.Close(); 
      socket.Close(); 
     } 
    } 
} 

ありがとうございます。

+0

「複数のスレッドを試しましたが、失敗しました」 - どのように試しましたか、どのような問題がありましたか? StartServer()が返されるまで、アプリケーションは応答しなくなります。これは、着信接続を受け入れてデータを返すのにかかる時間によって異なります。 (ソケットはデフォルトでブロックされています) –

+0

button1_Clickイベントでスレッドを呼び出しました。問題は同じ形が凍っていたことでした。 –

答えて

5

アプリケーションは、button1_Clickが返されるまでブロックします。

リスニングを行うにはワーカースレッドを生成する必要があります。さらに、コントロールをワーカースレッドに直接渡すべきではありません。むしろ、ソケット通信から得られるデータをコントロールに取り込むコールバックが必要です。

BackgroundWorkerに関する情報を検索します。これは、あなたが行く必要がある場所にあなたを取得します。

0

私はあなたがtxtStatusという名前のWindowsフォームだけで一つの制御のTextViewに配置する必要があります、SERVER

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 
using System.Windows.Forms; 

using System.Net; 
using System.Net.Sockets; 


using System.Threading; 

namespace SERVER_WIN 
{ 
    public partial class Form1 : Form 
    { 

     //Declare and Initialize the IP Adress 
     static IPAddress ipAd = IPAddress.Parse("10.1.42.31"); 

     //Declare and Initilize the Port Number; 
     static int PortNumber = 8888; 

     /* Initializes the Listener */ 
     TcpListener ServerListener = new TcpListener(ipAd, PortNumber); 
     TcpClient clientSocket = default(TcpClient); 

     public Form1() 
     { 
      InitializeComponent(); 
     } 

     private void Form1_Load(object sender, EventArgs e) 
     { 
      Thread ThreadingServer = new Thread(StartServer); 
      ThreadingServer.Start(); 
     } 

     private void THREAD_MOD(string teste) 
     { 
      txtStatus.Text += Environment.NewLine + teste; 
     } 

     private void StartServer() 
     { 
      Action<string> DelegateTeste_ModifyText = THREAD_MOD;    
      ServerListener.Start(); 
      Invoke(DelegateTeste_ModifyText, "Server waiting connections!"); 
      clientSocket = ServerListener.AcceptTcpClient(); 
      Invoke(DelegateTeste_ModifyText, "Server ready!"); 

      while (true) 
      { 
       try 
       { 

        NetworkStream networkStream = clientSocket.GetStream(); 
        byte[] bytesFrom = new byte[20]; 
        networkStream.Read(bytesFrom, 0, 20); 
        string dataFromClient = System.Text.Encoding.ASCII.GetString(bytesFrom); 
        dataFromClient = dataFromClient.Substring(0, dataFromClient.IndexOf("$")); 

        string serverResponse = "Received!"; 
        Byte[] sendBytes = Encoding.ASCII.GetBytes(serverResponse); 
        networkStream.Write(sendBytes, 0, sendBytes.Length); 
        networkStream.Flush(); 
       } 
       catch 
       { 
        ServerListener.Stop(); 
        ServerListener.Start(); 
        Invoke(DelegateTeste_ModifyText, "Server waiting connections!"); 
        clientSocket = ServerListener.AcceptTcpClient(); 
        Invoke(DelegateTeste_ModifyText, "Server ready!"); 
       } 

      } 
     } 
    } 
} 

のための私の解決策に従って、同じ問題を抱えていました。

クライアントプログラム:あなたはいくつかのコントロールを置く必要があります。クライアントのために

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 
using System.Windows.Forms; 

using System.Net; 
using System.Net.Sockets; 
using System.IO; 

namespace CLIENT_WIN 
{ 
    public partial class Form1 : Form 
    { 
     TcpClient tcpclnt = new TcpClient(); 

     //Declare and Initialize the IP Adress 
     IPAddress ipAd = IPAddress.Parse("10.1.42.31"); 

     //Declare and Initilize the Port Number; 
     int PortNumber = 8888; 

     public Form1() 
     { 
      InitializeComponent(); 

     } 

     private void Form1_Load(object sender, EventArgs e) 
     { 
      Console.WriteLine("Connecting....."); 
      try 
      { 
       tcpclnt.Connect(ipAd, PortNumber); 
       txtStatus.Text += Environment.NewLine + "Connected"; 
       txtStatus.Text += Environment.NewLine + "Enter the string to be transmitted"; 
      } 
      catch { } 
     } 

     private void btnEnviar_Click(object sender, EventArgs e) 
     { 
      String str = txtEnviar.Text + "$"; 
      Stream stm = tcpclnt.GetStream(); 

      ASCIIEncoding asen = new ASCIIEncoding(); 
      byte[] ba = asen.GetBytes(str); 

      txtStatus.Text += Environment.NewLine + "Transmitting..."; 
      //Console.WriteLine("Transmitting....."); 

      stm.Write(ba, 0, ba.Length); 

      byte[] bb = new byte[100]; 
      int k = stm.Read(bb, 0, 100); 

      string Response = Encoding.ASCII.GetString(bb); 

      txtStatus.Text += Environment.NewLine + "Response from server: " + Response; 

     } 
    } 
} 

。 2つのTextView(txtStatusとtxtEnviar)とbtnEnviarというボタンがあります。

クライアントを停止する必要がある場合は、最初にサーバーを実行する必要があります。クライアントを実行すると、サーバーを実行させることができます。

関連する問題