Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# socket server with windows form application

Tags:

c#

sockets

I searched a lot but all examples in the internet are console application. I've tried use console application example for windows forms but when I call socket.start form freezes and status changes to (not response). Also I tried multiple threads but it's unsuccessful too. If it is possible please advice me something.

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();
        }
    }
}

Thanks.

like image 744
Teymur Hacizade Avatar asked May 03 '12 19:05

Teymur Hacizade


1 Answers

Your application will block until button1_Click returns.

You need to spawn a worker thread to do your listening. Additionally, you should not pass your controls directly into the worker thread. Rather, you should have a callback that will populate your controls with the data that comes from the socket communications.

Look up information on the BackgroundWorker. This will get you where you need to go.

like image 184
Sean H Avatar answered Sep 30 '22 02:09

Sean H