2012-04-16 11 views
12

Tengo una tarea para construir una aplicación que enviará y recibirá cadena simple entre el servidor y el cliente. Sé cómo establecer una conexión, pero no sé cómo enviar y recibir una cadena. Este es mi código:Server Client envía/recibe texto simple

public partial class Form1 : Form 
{ 
    private Thread n_server; 
    private Thread n_client; 
    private Thread n_send_server; 
    private TcpClient client; 
    private TcpListener listener; 
    private int port = 2222; 
    private string IP = " "; 
    private Socket socket; 
    public Form1() 
    { 
     InitializeComponent(); 
    } 

    private void exitToolStripMenuItem_Click(object sender, EventArgs e) 
    { 
     Application.Exit(); 
    } 

    public void Server() 
    { 
     listener = new TcpListener(IPAddress.Any, port); 
     listener.Start(); 
     try 
     { 
      socket = listener.AcceptSocket(); 
      if (socket.Connected) 
      { 
       textBox2.Invoke((MethodInvoker)delegate { textBox2.Text = "Client : " + socket.RemoteEndPoint.ToString(); }); 
      } 
     } 
     catch 
     { 
     } 
    } 

    public void Client() 
    { 
     IP = "localhost"; 
     client = new TcpClient(); 
     try 
     { 
      client.Connect(IP, port); 
     } 

     catch (Exception ex) 
     { 
      MessageBox.Show("Error : " + ex.Message); 
     } 

     if (client.Connected) 
     { 
      textBox3.Invoke((MethodInvoker)delegate { textBox3.Text = "Connected..."; }); 

     } 
    } 

    private void button1_Click(object sender, EventArgs e) 
    { 
     n_server = new Thread(new ThreadStart(Server)); 
     n_server.IsBackground = true; 
     n_server.Start(); 
     textBox1.Text = "Server up"; 
    } 

    private void button2_Click(object sender, EventArgs e) 
    { 
     n_client = new Thread(new ThreadStart(Client)); 
     n_client.IsBackground = true; 
     n_client.Start(); 
    } 

    private void send() 
    { 
     // I want to use this method for both buttons : "send button" on server side and "send button" 
     // on client side. First I read text from textbox2 on server side or textbox3 
     // on client side than accept and write the string to label2(s) or label3(c). 
     // 
    } 


    private void button3_Click(object sender, EventArgs e) 
    { 
     n_send_server = new Thread(new ThreadStart(send)); 
     n_send_server.IsBackground = true; 
     n_send_server.Start(); 
    } 
} 

Respuesta

46

El siguiente código de envío y reciba la fecha y hora actuales desde y hacia el servidor

// El código siguiente es para la aplicación de servidor:

namespace Server 
{ 
    class Program 
    { 
     const int PORT_NO = 5000; 
     const string SERVER_IP = "127.0.0.1"; 

     static void Main(string[] args) 
     { 
      //---listen at the specified IP and port no.--- 
      IPAddress localAdd = IPAddress.Parse(SERVER_IP); 
      TcpListener listener = new TcpListener(localAdd, PORT_NO); 
      Console.WriteLine("Listening..."); 
      listener.Start(); 

      //---incoming client connected--- 
      TcpClient client = listener.AcceptTcpClient(); 

      //---get the incoming data through a network stream--- 
      NetworkStream nwStream = client.GetStream(); 
      byte[] buffer = new byte[client.ReceiveBufferSize]; 

      //---read incoming stream--- 
      int bytesRead = nwStream.Read(buffer, 0, client.ReceiveBufferSize); 

      //---convert the data received into a string--- 
      string dataReceived = Encoding.ASCII.GetString(buffer, 0, bytesRead); 
      Console.WriteLine("Received : " + dataReceived); 

      //---write back the text to the client--- 
      Console.WriteLine("Sending back : " + dataReceived); 
      nwStream.Write(buffer, 0, bytesRead); 
      client.Close(); 
      listener.Stop(); 
      Console.ReadLine(); 
     } 
    } 
} 

// este es el código para el cliente

namespace Client 
{ 
    class Program 
    { 
     const int PORT_NO = 5000; 
     const string SERVER_IP = "127.0.0.1"; 
     static void Main(string[] args) 
     { 
      //---data to send to the server--- 
      string textToSend = DateTime.Now.ToString(); 

      //---create a TCPClient object at the IP and port no.--- 
      TcpClient client = new TcpClient(SERVER_IP, PORT_NO); 
      NetworkStream nwStream = client.GetStream(); 
      byte[] bytesToSend = ASCIIEncoding.ASCII.GetBytes(textToSend); 

      //---send the text--- 
      Console.WriteLine("Sending : " + textToSend); 
      nwStream.Write(bytesToSend, 0, bytesToSend.Length); 

      //---read back the text--- 
      byte[] bytesToRead = new byte[client.ReceiveBufferSize]; 
      int bytesRead = nwStream.Read(bytesToRead, 0, client.ReceiveBufferSize); 
      Console.WriteLine("Received : " + Encoding.ASCII.GetString(bytesToRead, 0, bytesRead)); 
      Console.ReadLine(); 
      client.Close(); 
     } 
    } 
} 
+1

este código se está trabajando o probado ..? – SANDEEP

+4

Hola @SANDEEP el código funciona como un amuleto. Probé antes de enviarlo. –

+0

¿Por qué solo puedo leer el primer mensaje devuelto por el servidor? La próxima vez que llamo _nwStream.Read_ no devuelve ningún valor. Cuando configuro el punto de depuración, no puedo ir a la siguiente línea, no se lanza ninguna excepción. – Hp93

-2

cLIENTE

SocketKlient espacio de nombre

{ class Program

{ 
    static Socket Klient; 
    static IPEndPoint endPoint; 
    static void Main(string[] args) 
    { 
     Klient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); 
     string command; 
     Console.WriteLine("Write IP address"); 
     command = Console.ReadLine(); 
     IPAddress Address; 
     while(!IPAddress.TryParse(command, out Address)) 
     { 
      Console.WriteLine("wrong IP format"); 
      command = Console.ReadLine(); 
     } 
     Console.WriteLine("Write port"); 
     command = Console.ReadLine(); 

     int port; 
     while (!int.TryParse(command, out port) && port > 0) 
     { 
      Console.WriteLine("Wrong port number"); 
      command = Console.ReadLine(); 
     } 
     endPoint = new IPEndPoint(Address, port); 
     ConnectC(Address, port); 
     while(Klient.Connected) 
     { 
      Console.ReadLine(); 
      Odesli(); 
     } 
    } 

    public static void ConnectC(IPAddress ip, int port) 
    { 
     IPEndPoint endPoint = new IPEndPoint(ip, port); 
     Console.WriteLine("Connecting..."); 
     try 
     { 
      Klient.Connect(endPoint); 
      Console.WriteLine("Connected!"); 
     } 
     catch 
     { 
      Console.WriteLine("Connection fail!"); 
      return; 
     } 
     Task t = new Task(WaitForMessages); 
     t.Start(); 
    } 

    public static void SendM() 
    { 
     string message = "Actualy date is " + DateTime.Now; 
     byte[] buffer = Encoding.UTF8.GetBytes(message); 
     Console.WriteLine("Sending: " + message); 
     Klient.Send(buffer); 
    } 

    public static void WaitForMessages() 
    { 
     try 
     { 
      while (true) 
      { 
       byte[] buffer = new byte[64]; 
       Console.WriteLine("Waiting for answer"); 
       Klient.Receive(buffer, 0, buffer.Length, 0); 

       string message = Encoding.UTF8.GetString(buffer); 
       Console.WriteLine("Answer: " + message); 
      } 
     } 
     catch 
     { 
      Console.WriteLine("Disconnected"); 
     } 
    } 
} 

}

+2

Por favor, no publique solo el código de respuestas. Tu respuesta debe incluir una explicación sobre por qué funciona. – Milk

+1

También debe incluir tanto el código del cliente como el del servidor en una sola respuesta. No dos. –

-2

SERVIDOR

SocketServer espacio de nombre

{ class Program

{ 
    static Socket klient; 
    static void Main(string[] args) 
    { 
     Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); 
     IPEndPoint endPoint = new IPEndPoint(IPAddress.Any, 8888); 
     server.Bind(endPoint); 
     server.Listen(20); 
     while(true) 
     { 
      Console.WriteLine("Waiting..."); 
      klient = server.Accept(); 

      Console.WriteLine("Client connected"); 
      Task t = new Task(ServisClient); 
      t.Start(); 
     } 
    } 

    static void ServisClient() 
    { 
     try 
     { 
      while (true) 
      { 
       byte[] buffer = new byte[64]; 
       Console.WriteLine("Waiting for answer..."); 
       klient.Receive(buffer, 0, buffer.Length, 0); 
       string message = Encoding.UTF8.GetString(buffer); 
       Console.WriteLine("Answer: " + message); 

       string answer = "Actualy date is " + DateTime.Now; 
       buffer = Encoding.UTF8.GetBytes(answer); 
       Console.WriteLine("Sending {0}", answer); 
       klient.Send(buffer); 
      } 
     } 
     catch 
     { 
      Console.WriteLine("Disconnected"); 
     } 
    } 
} 

}