Dave

Dave

  • NA
  • 48
  • 24k

Learning System.Net.Sockets

Aug 21 2010 12:04 AM

Hi,
I wrote a very simple C# program, using System.Net.Sockets to send a message in the same form.
However, I must misunderstood something, it was not working:
when clicked button1, the forrm displayed "Not Responding". Can you tell me what I was doing wrong?
using System;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.IO;
namespace SocketA
{
    public partial class Form1 : Form
    {
        TcpListener server;
        TcpClient client;
        NetworkStream netStream;
        public Form1()
        {
            InitializeComponent();
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            try
            {
                Int32 port = 13000;
                IPAddress localAddr = IPAddress.Parse("127.0.0.1");
                server = new TcpListener(localAddr, port);
                server.Start();
                //client = server.AcceptTcpClient();
                client = new TcpClient("127.0.0.1", port);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        private void button1_Click(object sender, EventArgs e)
        {
            netStream = client.GetStream();
            StreamWriter sw = new StreamWriter(netStream);
            StreamReader sr = new StreamReader(netStream);
            sw.Write("sssssssss");
            try
            {
                textBox1.Text = sr.ReadLine();
                sw.Flush();
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message);
                client.Close();
            }
        }
    }
}

Answers (1)