private void btStart_Click(object sender, EventArgs e) { // Start listening... if (!listening) { // Check if tbPort.Text is a correct number int listeningPort; if (int.TryParse(tbPort.Text, out listeningPort)) { if (listeningPort > 0 && listeningPort < 65768) { // Create listening socket and bind it to Any:PORT IPAddress listeningIp = IPAddress.Any; IPEndPoint listeningEndPoint = new IPEndPoint(listeningIp, listeningPort); listeningSocket = new Socket(listeningIp.AddressFamily, SocketType.Stream, ProtocolType.Tcp); listeningSocket.Bind(listeningEndPoint); listeningSocket.Listen(10); // Start thread to handle incoming connections SocketHandler socketHandler = new SocketHandler(listeningSocket, this); serverThread = new Thread(new ThreadStart(socketHandler.startListening)); serverThread.Start(); log("Listening on port " + listeningPort); btStart.Text = "Stop listening"; tbPort.ReadOnly = true; listening = true; } } else { MessageBox.Show("Invalid port number", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } // Stop listening... else { listeningSocket.Close(); serverThread.Abort(); log("Listening stopped"); btStart.Text = "Start listening"; tbPort.ReadOnly = false; listening = false; } }
private void btStart_Click(object sender, EventArgs e) { // Start listening... if (!listening) { // Check if tbPort.Text is a correct number int listeningPort; if (int.TryParse(tbPort.Text, out listeningPort)) { if (listeningPort > 0 && listeningPort < 65768) { // Create listening socket and bind it to Any:PORT IPAddress listeningIp = IPAddress.Any; IPEndPoint listeningEndPoint = new IPEndPoint(listeningIp, listeningPort); listeningSocket = new Socket(listeningIp.AddressFamily, SocketType.Stream, ProtocolType.Tcp); listeningSocket.Bind(listeningEndPoint); listeningSocket.Listen(10); // Start thread to handle incoming connections SocketHandler socketHandler = new SocketHandler(listeningSocket, this); serverThread = new Thread(new ThreadStart(socketHandler.startListening)); serverThread.Start(); log("Listening on port " + listeningPort); btStart.Text = "Stop listening"; tbPort.ReadOnly = true; listening = true; } } else MessageBox.Show("Invalid port number", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } // Stop listening... else { listeningSocket.Close(); serverThread.Abort(); log("Listening stopped"); btStart.Text = "Start listening"; tbPort.ReadOnly = false; listening = false; } }