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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With