As with Java we can use C# to handle Sockets in our computers. The Socket Basics are the same as described in here.
But
there are some different key words which C# use to play with Sockets.
Some of them are described as below. (Found them on the internet). They
will give some brief explanation about those words. (Actually those
words represent C# classes and Methods)
GetStream returns a NetworkStream
that you can use to send and receive data. The NetworkStream class inherits
from the Stream
class, which provides a rich collection of methods and properties used to
facilitate network communications.
The NetworkStream class
provides methods for sending and receiving data over Stream sockets in blocking
mode.
You must call the Connect method first, or the GetStream
method will throw an InvalidOperationException. After you have obtained
the NetworkStream,
call the Write method to send data to the remote host. Call the Read method to
receive data arriving from the remote host. Both of these methods block until
the specified operation is performed. You can avoid blocking on a read
operation by checking the DataAvailable property. A true value means that data
has arrived from the remote host and is available for reading. In this case,
Read is guaranteed to complete immediately. If the remote host has shutdown its
connection, Read will immediately return with zero bytes.
You must close the NetworkStream when you are through
sending and receiving data. Closing TcpClient does not release the
NetworkStream.
The TcpClient class provides
simple methods for connecting, sending, and receiving stream data over a
network in synchronous blocking mode.
The TcpListener class provides simple
methods that listen for and accept incoming connection requests in blocking
synchronous mode. You can use either a TcpClient or a Socket to connect with a
TcpListener. Create a TcpListener using an IPEndPoint, a Local IP
address and port number, or just a port number. Specify Any for the local IP
address and 0 for the local port number if you want the underlying service
provider to assign those values for you. If you choose to do this, you can use
the LocalEndpoint
to identify the assigned information.
Use the Start method to begin listening for incoming
connection requests. Start will queue incoming connections until you
either call the Stop method or it has queued MaxConnections. Use either
AcceptSocket or AcceptTcpClient to pull a connection from the incoming
connection request queue. These two methods will block. If you want to avoid
blocking, you can use the Pending method first to determine if connection
requests are available in the queue.
Call the Stop method to close the TcpListener.
The Stop method does not close any accepted connections.
You are responsible for closing these separately.
Before
jump in to the code, we have to make sure that all the required C#
name spaces are inserted in to the project source files.
normally C# project source file contains ( by default ) some name spaces.
they are :
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
We have to add additional 3 name spaces to the file. They are :
- using System.IO;
- using System.Net;
- using System.Net.Sockets;
Server Code
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using System.Net; using System.Net.Sockets; namespace server { class Program { static void Main(string[] args) { TcpClient AcceptedClient; NetworkStream instream; TcpListener clientListner = new TcpListener(IPAddress.Parse("127.0.0.1"), 7000); clientListner.Stop(); clientListner.Start(); while (true) { if (clientListner.Pending()) { // when the client connected to the port, this will //return that client as the Accepted client AcceptedClient = clientListner.AcceptTcpClient(); // get the Accepted client's NetworkStream, //we want that to read data, which client is sending instream = AcceptedClient.GetStream(); // read the input data into a byte list. //(lets read byte at a time) BinaryReader reader = new BinaryReader(instream); ListinputStr = new List (); int a = 0; while (a != -1) { try { a = reader.ReadByte(); inputStr.Add((Byte)a); } catch (Exception e) { break; } } // make a full string and write to Console string s = Encoding.ASCII.GetString(inputStr.ToArray()); Console.Write(s); } } } } }
Client Code
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using System.Net; using System.Net.Sockets; namespace client { class Program { static void Main(string[] args) { NetworkStream outStream; StreamWriter writer; TcpClient client = new TcpClient(); // client is trying to connect to the given ip address and port // so this client will be catched by the //TcpLstner of server program client.Connect(IPAddress.Parse("127.0.0.1"),7000); // get the Network stream, we have to send data outStream = client.GetStream(); // make the writer writer = new StreamWriter(outStream); Console.Write("Enter your name : "); string name = Console.ReadLine(); writer.Write(name); // finally Flush and Close writer.Flush(); writer.Close(); outStream.Close(); client.Close(); } } }
0 comments:
Post a Comment