PDA

View Full Version : Reading and Writing TCP sockets in C#



Adrenalynn
08-27-2008, 07:55 PM
Several people have independantly asked me something along the lines of: "Do you know how to communicate over the network with C#?"

Yes. I do. :) Now you will too.

This first VERY simple stand-alone console server app will listen on a free port and echo one line sent from a client to the console, then wait for a newline to exit.

Not production code, just the cheapest easiest way I know of to open a listening TCP socket and grab some data.

The next post to follow as soon as I write the code will be the client side, which will just simply open a socket and blast some data to our server.

You can test this server without the accompanying client by doing a:

telnet [my ip address] [my port number]

As written here: telnet 192.168.0.100 9090 [enter]

Type in some next, hit enter, the server then echos it. It's even more exciting when the server is living on a different machine than the telnet client. :) Congrats! Your first TCP session! Woot! :D I tested it connecting from a linux box to the windows box. I even tested it connecting from my phone to the winders machine. Double Woot!



// A spiffy little stand-alone TCP server in C# that will read one line of text and echo it to the console.
// Not much to see here, just an illustration of how to begin exploring socket communication in C# dotNet.
// jlr - August 27, 2008
using System;
using System.Text;
using System.Collections.Generic;
using System.Net.Sockets;

namespace OurSpiffyServer_ConsoleApp
{
class Program
{
const int Port = 9090; // The port number we're going to listen on. Any unused port < 65534 preferably above 1024 (protected ports)
static void Main(string[] args)
{
// Our local IP address - you'll be wanting to change this...
System.Net.IPAddress serverAddress = System.Net.IPAddress.Parse("192.168.0.100"); // <-- Change that as appropriate!

// Start listening for connections on our IP address + Our Port number
TcpListener listener = newTcpListener(serverAddress, Port);
listener.Start();

// Is someone trying to call us? Well answer!
TcpClient ourTCP_Client = listener.AcceptTcpClient();

//A network stream object. We'll use this to send and receive our data, so create a buffer for it...
NetworkStream ourStream = ourTCP_Client.GetStream();
byte[] data = newbyte[ourTCP_Client.ReceiveBufferSize];

// read the incoming data stream - note that Read() is a blocking call...
int bytesRead = ourStream.Read(data, 0, System.Convert.ToInt32(ourTCP_Client.ReceiveBuffer Size));
// echo the data we got to the console until the newline, and delay closing our window.
Console.WriteLine("Received : " + Encoding.ASCII.GetString(data, 0, bytesRead));
Console.ReadLine();
}
}
}


I think the code is pretty self-documenting. Questions? Ask away!

[edit] Sorry - this thing REALLY refuses to maintain my pretty formatting, even in a code tag. Grrrrr.

Adrenalynn
08-27-2008, 09:21 PM
Client Time!

Betcha I don't need any intro or further documentation for this one. Look at how easy this is:



using System;
using System.Text;
using System.Collections.Generic;
using System.Net.Sockets;

namespace consoleTCPClient
{
class Program
{
const int ourPort = 9090; // This needs to match the server's port
static void Main(string[] args)
{
TcpClient ourMagicClient = new TcpClient();

//Connect to the server - change this IP address to match your server's IP!
ourMagicClient.Connect("192.168.0.100", ourPort);

//Use a NetworkStream object to send and/or receive some data
NetworkStream ourStream = ourMagicClient.GetStream();

//Let's set up some data!
byte[] data = Encoding.ASCII.GetBytes("What a cute widdle robot you have there!");

//Everyone ready? Send that bad-boy!
ourStream.Write(data, 0, data.Length); //Start at the 0'th position in our string and send until the end of the string, but we can stop there...
}
}
}

* Not even gonna bother trying to format this. . .

aatif
03-02-2009, 03:02 AM
Hello,
I am new to Socket programming in C#. My question is, can I use two sockets in my client app, one for writing (question) and the other for listening (the answer), against a same server application?

Adrenalynn
03-02-2009, 04:32 AM
Welcome to the forum!

Sure, in theory you can open as many ports (<64k) as you want, that aren't already in use. You can read and write to them as you see fit. Basically, you're just implementing read to one, write to the other, inverted on each end from the other.

I'm not necessarily seeing any advantages to that at first blush, but I'm sure you have a good reason. :)

zenedee
11-12-2012, 03:13 AM
Hello,
I am new to Socket programming in C#. My question is, can I use two sockets in my client app, one for writing (question) and the other for listening (the answer), against a same server application?

Ofcourse , you can connect one more clients at the same time to a socket server. check the following simple socket programming sample. http://csharp.net-informations.com/communications/csharp-socket-programming.htm it is easy to understand the basics of socket programming.

zene.

sahmed21
08-07-2013, 05:31 AM
the code is great but i have one issue that when i run this it gives me error "The requested address is not valid in its context".
Please do rep asap i have to complete this task in a hurry !!

gromit
08-07-2013, 12:15 PM
Done many times with many examples online.

https://encrypted.google.com/webhp?source=search_app#bav=on.2,or.r_qf.&fp=e7239e6f7a50ac15&q=c%23+socket+server+example