User Tools

Site Tools


trainningcsharpsocketclient
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication2
{
  public partial class Form1 : Form
  {
      public Form1()
      {
          InitializeComponent();
      }
      private void button1_Click(object sender, EventArgs e)
      {
          String server = textBox1.Text;
          String message = textBox2.Text;
          try
          {
              // Create a TcpClient. 
              // Note, for this client to work you need to have a TcpServer  
              // connected to the same address as specified by the server, port 
              // combination.
              Int32 port = 13000;
              TcpClient client = new TcpClient(server, port);
              // Translate the passed message into ASCII and store it as a Byte array.
              Byte[] data = System.Text.Encoding.ASCII.GetBytes(message);
              // Get a client stream for reading and writing. 
              //  Stream stream = client.GetStream();
              NetworkStream stream = client.GetStream();
              // Send the message to the connected TcpServer. 
              stream.Write(data, 0, data.Length);
              Console.WriteLine("Sent: {0}", message);
              // Receive the TcpServer.response. 
              // Buffer to store the response bytes.
              data = new Byte[256];
              // String to store the response ASCII representation.
              String responseData = String.Empty;
              // Read the first batch of the TcpServer response bytes.
              Int32 bytes = stream.Read(data, 0, data.Length);
              responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes);
              textBox3.Text = textBox3.Text + responseData;
              Console.WriteLine("Received: {0}", responseData);
              // Close everything.
              stream.Close();
              client.Close();
          }
          catch (ArgumentNullException ex)
          {
              Console.WriteLine("ArgumentNullException: {0}", ex);
          }
          catch (SocketException ex)
          {
              Console.WriteLine("SocketException: {0}", ex);
          }
          Console.WriteLine("\n Press Enter to continue...");
          Console.Read();
      }
  }
}
trainningcsharpsocketclient.txt · Last modified: 2014/03/02 14:21 (external edit)