Created
September 21, 2011 06:47
-
-
Save msbukkuri/1231421 to your computer and use it in GitHub Desktop.
Random Socket Code Example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public partial class Form1 : Form | |
{ | |
private List<Socket> clients = new List<Socket>(); | |
private Thread listening_thread; | |
private TcpListener listener; | |
public Form1() | |
{ | |
InitializeComponent(); | |
this.listening_thread = new Thread(new ThreadStart(this.ListeningThread)); | |
this.listening_thread.Start(); | |
} | |
private void ListeningThread() // let's listen in another thread instead!! | |
{ | |
int port = 12345; // change as required | |
this.listener = new TcpListener(IPAddress.Any, port); | |
try | |
{ | |
this.listener.Start(); | |
} | |
catch (Exception e) { MessageBox.Show("couldn't bind to port " + port + " -> " + e.Message); return; } | |
while (true) | |
{ | |
if (this.listener.Pending()) | |
this.clients.Add(this.listener.AcceptSocket()); // won't block because pending was true | |
foreach (Socket sock in this.clients) | |
if (sock.Poll(0, SelectMode.SelectError)) | |
clients.Remove(sock); | |
else if (sock.Poll(0, SelectMode.SelectRead)) | |
ParserFunction(sock); | |
Thread.Sleep(30); | |
} | |
} | |
private void ParserFunction(Socket sock) | |
{ | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment