"Reprint" C # tutorial-simple threaded TCP Server

Source: Internet
Author: User
Tags getstream socket error

Http://tech.pro/tutorial/704/csharp-tutorial-simple-threaded-tcp-server

In this tutorial I ' m going to show what you do to build a threaded TCP server with C #. If you've ever worked with Window's sockets, you know how difficult the can sometimes be. However, thanks to the. NET framework, making one are a lot easier than it used to be.

What we'll be building today is a very simple server that accepts client connections and can send and receive data. The server spawns a thread for each client and can, in theory, accept as many connections as you want (although in practic E This was limited because you can only spawn so many threads before Windows would get upset).

Let's just jump into some code. Below is the basic setup for our TCP server class.

Using System;Using System.Text;Using System.Net.Sockets;Using System.Threading;Using System.Net;Namespace Tcpservertutorial{ Class Server { Private TcpListenerTcpListener; Private ThreadListenthread; Public Server() { This.TcpListener= New TcpListener(IPAddressany, 3000); this. Listenthread = new  Thread (new threadstart listenforclientsthis. Listenthread. Start} }}    /span>                

So here ' s a basic server class-without the guts. We ' ve got a tcplistener which does a good job of wrapping up the underlying socket communication, and a Thread which would Is listening for client connections. You might has noticed the function, which is used for our ListenForClients ThreadStart delegate. Let's see what's looks like.

Private void Listenforclients(){ This.TcpListener.Start(); While (True) { Blocks until a client have connected to the server TcpClientClient= This.TcpListeneraccepttcpclient (); //create a thread to handle communication  //with connected Client thread Clientthread =  new thread ( new parameterizedthreadstart ( handleclientcomm Clientthread. Startclient}}          /span>                

This function was pretty simple. First it starts our tcplistener and then sits in a loop accepting connections. AcceptTcpClientthe call to would block until a client have connected, at which point we fire off a thread to handle communication wit H our new client. I used a Parameterizedthreadstart delegate so I could pass the TcpClient object returned by the accepttcpclient call to OU R new Thread.

The function I used for the Parameterizedthreadstart is called HandleClientComm . This function is a responsible for reading data from the client. Let ' s has a look at it.

Private void Handleclientcomm(ObjectClient){ TcpClientTcpClient= (TcpClient)Client; NetworkStreamClientstream=TcpClient.GetStream(); Byte[]Message= New Byte[4096]; IntBytesread; While (True) {Bytesread= 0; Try { Blocks until a client sends a messageBytesread=Clientstream.Read(Message, 0, 4096); } Catch { A socket error has occured Break; } If (Bytesread== 0) { The client has disconnected from the server Break; } Message has successfully been received ASCIIEncodingEncoder= new asciiencoding< Span class= "pun" > ();  system. Diagnostics. Debug. Writeline (encoder. Getstring (message, 0< Span class= "pun" >, Bytesread } Tcpclient. Close               /span>                

The first thing we need to does is cast  client  as a TcpClient object since the Parameterizedthread Start delegate can only accept object types. Next, we get Thenetworkstream from the TcpClient, which we'll be using and to does our reading. After, we simply sit in a while true loops reading information from the client. the  Read  call would block indefinitely until a message from the client has been received. If you read zero bytes from the client, you know the client have disconnected. Otherwise, a message has been successfully received from the server. In my example code, I simply convert the byte array to a string and push it to the debug console. You'll, of course, do something more interesting with the data-i hope. If the socket has a error or the client disconnects, you should call  Close  on the TcpClient object To a any of the resources it was using.

Believe it or not, that's pretty much all need to do to the create a threaded server that accepts connections and reads Da Ta from clients. However, a server isn ' t very useful if it can ' t send data back, so let's look at how to send the data to one of our connected Clients.

NetworkStreamClientstream=TcpClient.GetStream();ASCIIEncodingEncoder= new asciiencoding (); Span class= "PLN" >byte[] buffer = Encoder. Getbytes ( "Hello client!" clientstream. Write (buffer, 0 , Buffer. Lengthclientstream. Flush              

Do you remember the TcpClient object, is returned from the call accepttcpclient? Well, that's the object we'll be using to send data back to the client. That's being said, you'll probably want to keep those objects around somewhere in your server. I usually keep a collection of TcpClient objects that I can use later. Sending data to connected clients are very simple. All of the Write NetworkStream object and pass it the byte array you ' d ' A to send.

Your TCP Server is now finished. The hard part was defining a good protocol to use for sending information between the client and server. Application level protocols is generally unique for application, so I ' m not going to go into any details-you ' ll just ha ve to invent you ' re own.

What if use is a server without a client to connect to it? This tutorial was mainly about the server, but here's a quick piece of code that shows what to set up a basic TCP Connec tion and send it a piece of data.

TcpClientClient= New TcpClient();IPEndPointServerendpoint= New IPEndPoint(IPAddress.Parse("127.0.0.1"), 3000);Client.Connect(Serverendpoint);NetworkStreamClientstream=Client.GetStream();ASCIIEncodingEncoder= new asciiencoding (); Span class= "PLN" >byte[] buffer = Encoder. Getbytes ( "Hello server!" clientstream. Write (buffer, 0 , Buffer. Lengthclientstream. Flush              

The first thing we need to do are get the client connected to the server. We use the Tcpclient.connect method to does this. It needs the ipendpoint of our servers to make the connection-in this case I connect it to localhost on Port 3000. I then simply send the server the string "Hello server!".

One very important thing to remember are that one write from the client or server does don't always equal one read on the rec Eiving end. For instance, your client could send a bytes to the server, but the server could not get all bytes the first time it rea Ds. Using TCP, you're pretty much guaranteed to eventually get all ten bytes, but it might take more than one read. You should keep this in mind when designing your protocol.

That ' s it! Now get out there and clog the tubes with your fancy new C # TCP servers.

"Reprint" C # tutorial-simple threaded TCP Server

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.