CaTx
CaTx

Reputation: 1481

TCP client/server with C# .Net

I am following this example of TCP client/server

www.codeproject.com/Articles/1415/Introduction-to-TCP-client-server-in-C

I am more familiar with WinForms than console application, so I decide to remake the code in WinForms. I have the client and server code in the same form. When initialize the server, the form is stuck after I use AcceptSocket(), and I cannot use an button to initiate action from the client side. Does this mean that I have to code the client and server in separate WinForms? =/

Upvotes: 0

Views: 1535

Answers (2)

cHao
cHao

Reputation: 86505

You need to be able to read the socket without tying up your UI thread. Otherwise, the window appears unresponsive.

You have two choices for that. The first, and ostensibly easiest, is to use threads explicitly as already mentioned.

The second is to use one of the async versions of the accept/read/write functions (either BeginXXX/EndXXX or XXXAsync, depending on what API you use), which start up another thread from a thread pool for you. (The Async versions actually don't grab a thread til the event happens, while Begin/End might grab one immediately.) Unless you actually need to dedicate a new thread to watching a socket (and you almost never really do), i'd prefer the async stuff.

Either way, you're going to want to learn a little about multithreading. In this case, the big things you need to remember are that (1) no matter how you do it, your socket stuff is almost certainly going to be happening on another thread; and (2) WinForms controls hate being directly accessed from other threads; you'll need to use their Invoke method to make stuff happen on the UI thread instead.

Upvotes: 3

Jakub Konecki
Jakub Konecki

Reputation: 46008

You need to run them in separate threads. Make sure that you don't block the UI thread or the UI will become unresponsive.

Upvotes: 3

Related Questions