eembdersler.wordpress.com eembdersler.wordpress · connection oriented or connectionless. They can...
Transcript of eembdersler.wordpress.com eembdersler.wordpress · connection oriented or connectionless. They can...
1
http://http://eembdersler.wordpress.comeembdersler.wordpress.com
C.U ElectricalC.U Electrical--Electronics Eng. 20Electronics Eng. 2011 EEE11 EEE--448448
EEE-448COMPUTER NETWORKS
(Programming)
Turgay IBRIKCI, PhDEEE448 – Computer Networks
Spring 2011
Week -5C# With Computer
Networks
EEE448 – Computer NetworksSpring 2011
What’s the Internet: “nuts and bolts” view� millions of connected computing devices: hosts, end-systems� PCs workstations, servers� PDAs phones, toastersrunning network apps
� communication links� fiber, copper, radio, satellite
� transmission rate = bandwidth
� routers: forward packets (chunks of data)
local ISP
companynetwork
regional ISP
router workstationserver
mobile
What’s a protocol?
human protocols:� “what’s the time?”� “I have a question”� introductions
… specific msgs sent… specific actions taken when msgs received, or other events
network protocols:� machines rather than humans
� all communication activity in Internet governed by protocols
protocols define format, order of msgs sent and received among network entities, and actions
taken on msg transmission, receipt
What’s a protocol?
a human protocol and a computer network protocol:
Hi
Hi
Got thetime?2:00
TCP connectionreq
TCP connectionresponseGet http://www.cu.edu.tr/classesList.htm
<file>
time
A closer look at network structure:
� network edge:applications and hosts
� network core:� routers� network of networks
� access networks, physical media:communication links
2
http://http://eembdersler.wordpress.comeembdersler.wordpress.com
C.U ElectricalC.U Electrical--Electronics Eng. 20Electronics Eng. 2011 EEE11 EEE--448448
The communication can be either � connection oriented or � connectionless.
They can also be either� stream oriented or � data-gram based.
The most widely used protocol TCP is used for stream-based communication and UDP is used for data-grams based applications.
Internet transport protocols services
TCP service:� connection-oriented: setup required between client and server processes
� reliable transport between sending and receiving process
� flow control: sender won’t overwhelm receiver
� congestion control: throttle sender when network overloaded
� does not provide: timing, minimum bandwidth guarantees
UDP service:� unreliable data transfer between sending and receiving process
� does not provide: connection setup, reliability, flow control, congestion control, timing, or bandwidth guarantee
Q: why bother? Why is there a UDP?
Two essential types of sockets� SOCK_STREAM
� a.k.a. TCP� reliable delivery� in-order guaranteed� connection-oriented� bidirectional
� SOCK_DGRAM
� a.k.a. UDP� unreliable delivery� no order guarantees� no notion of “connection” –app indicates dest. for each packet
� can send or receiveApp
socket3 2 1
Dest.
App
socket3 2 1
D1
D3
D2
Q: why have type SOCK_DGRAM?
UDP Ports
� 16-bit unsigned integers associated with UDP connection
� Used to distinguish different processes running on the same host
InternetInternetAA BB
Proc1Proc1 Proc2Proc2 Proc3Proc3Proc4Proc4
Proc5Proc5
IP Address 1IP Address 1 IP Address 2IP Address 2
PortsPorts
Using UDP Sockets
Create a UDP socketCreate a UDP socket
Create a local endpointCreate a local endpoint
(Local IP + Local Port)(Local IP + Local Port)
Bind socket toBind socket to
the endpointthe endpoint
Receive dataReceive data
Close socketClose socket
Create a UDP socketCreate a UDP socket
Send dataSend data
Close socketClose socket
To receive dataTo receive data To send dataTo send data
Internet protocol stack
� application: supporting network applications� FTP, SMTP, STTP
� transport: host-host data transfer� TCP, UDP
� network: routing of datagrams from source to destination� IP, routing protocols
� link: data transfer between neighboring network elements� PPP, Ethernet
� physical: bits “on the wire”
application
transport
network
link
physical
3
http://http://eembdersler.wordpress.comeembdersler.wordpress.com
C.U ElectricalC.U Electrical--Electronics Eng. 20Electronics Eng. 2011 EEE11 EEE--448448
Application architectures� Client-server� Peer-to-peer (P2P)� Hybrid of client-server and P2P
Client-server architectureserver:
� always-on host� permanent IP address� server farms for scaling
clients:� communicate with server� may be intermittently connected
� may have dynamic IP addresses
� do not communicate directly with each other
Pure P2P architecture
� no always-on server� arbitrary end systems directly communicate
� peers are intermittently connected and change IP addresses
� Example:e-mule (File sharing)
Highly scalable but difficult to manage
Hybrid of client-server and P2PSkype
� Internet telephony app� Finding address of remote party: centralized server(s)� Client-client connection is direct (not through server)
Instant messaging� Chatting between two users is P2P� Presence detection/location centralized:
� User registers its IP address with central server when it comes online
� User contacts central server to find IP addresses of buddies
Processes communicating
Process: program running within a host.
� within same host, two processes communicate using inter-process communication (defined by OS).
� processes in different hosts communicate by exchanging messages
Client process: process that initiates communication
Server process: process that waits to be contacted
� Note: applications with P2P
architectures have client
processes & server processes
Finding IP Address Information
� One of the biggest challenges of network programming is dealing with network configurations of individual workstations and servers.
� When sending data across the network, you often need to determine the IP network information for the system running your program. The Windows family offers many ways to determine IP configuration information, both manually and from within a program.
4
http://http://eembdersler.wordpress.comeembdersler.wordpress.com
C.U ElectricalC.U Electrical--Electronics Eng. 20Electronics Eng. 2011 EEE11 EEE--448448
Watching Network Traffic� One of the biggest difficulties for network programmers is not being able to see exactly what is happening on the network.
� Often you think you have created the perfect client/server application, spending hours working out the mechanics of sending and receiving application data among machines, only to find out that somewhere along the network your data is not getting through.
� A network analyzer can be the network programmer’s best friend in finding out what is happening “on the wire.” Programming errors can often be detected by watching application data pass from one device to another
Some Programs
� http://www.winpcap.org/
� The WinPcap Programs� The WinPcap driver is the core of the package. It allows most types of network cards on a Windows workstation or server to be placed in promiscuous mode. In promiscuous mode, the network card can receive all traffic on the network, no matter where the packet is destined.
� The WinDump Program� It can either display a summary of each packet that it sees on the network, or a detailed hexadecimal dump of each packet’s contents. tcpdump uses simple command-line options to determine what type of packets to capture.
� Each IP line in the WinDump output contains the following information:� Timestamp� Source IP address (or hostname) and TCP or UDP port� Destination IP address (or hostname) and TCP or UDP port
� TCP or UDP packet information
Analyzing Network Packets� The ability to watch an IP session and decode its meaning is a crucial skill for a network programmer.
� To fully understand the concepts behind network programming
� The first layer of the network packet shown in the Analyzer capture is called the Ethernet header.
� You may see three types of Ethernet protocol packets on your network: � Ethernet 802.2, � Ethernet 802.3, and � Ethernet version 2.
5
http://http://eembdersler.wordpress.comeembdersler.wordpress.com
C.U ElectricalC.U Electrical--Electronics Eng. 20Electronics Eng. 2011 EEE11 EEE--448448
� The first layer of the network packet shown in the Analyzer capture is called the Ethernet header.
C# and Network Programming� The C# language provides you with all the tools necessary to quickly develop networked applications.
� Compared to C++ and Java� C# have a richer set of programming APIs� Eliminates most of the complexities previously associated with network programming
C# with Computer Networks� What Are Namespaces?� C# namespaces are used to identify a higher-level hierarchy of class names, allowing you to group similar classes together within a single namespace. The namespace is defined in the source code file before the class definition, using the namespace directive: namespace Test1;class testProgram{}namespace Test2;cclass testProgram{}
NamespacesNamespace Description of Classes
Microsoft.Win32 Handles events raised by the OS and Registry handling classes
System Base .NET classes that define commonly used data types and data conversions
System.Collections Defines lists, queues, bit arrays, and string collections
System.IO Allows reading and writing on data streams and files
System.Management Provides access to the Windows Management Instrumentation (WMI) infrastructure
System.Net Provides access to the Windows network functions
System.Net.Sockets Provides access to the Windows sockets (Winsock) interface
System.Runtime.Remoting Provides access to the Windows distributed computing platform
System.Security Provides access to the CLR security permissions system
System.Text Represents ACSII, Unicode, UTF-7, and UTF-8 character encodings
System.Threading Enables multi-threading programming
System.Web.Mail Enables sending mail messages
System.Windows.Forms Creates Windows-based application using the standard Windows graphical interface
Namespaces - II� Each namespace provides support for a specific group of classes.
� Once you have located the namespaces that contain the classes you need for your program,
� You must define them in your program to access the classes.
System.Net� Provides a simple programming interface to
� Many of the protocols found on the network today
� An implementation of network services that enables you to develop applications that use Internet resources
6
http://http://eembdersler.wordpress.comeembdersler.wordpress.com
C.U ElectricalC.U Electrical--Electronics Eng. 20Electronics Eng. 2011 EEE11 EEE--448448
System.Net� Primary Classes
– IPAddress : Provides an Internet Protocol (IP) address–SocketAddress : Identifies a socket address–Dns : Provides simple domain name resolution functionality–DnsPermission : Controls rights to access Domain Name System (DNS) servers on the network
System.Net
� Primary Classes (cnt.)
– HttpWebRequest, HttpWebResponse : HTTP implementation of request and response objects
– NetworkCredential : Credentials for password-based authentication schemes
– WebClient : Provides common methods for sending data to and receiving data from a resource identified by a URI
Namespaces in Programsusing System;namespace namespaces{
class MyClass { }}
class MainClass{
public static void Main(){namespaces.MyClass my = new namespaces.MyClass();}
}
Namespaces in Programs IIusing System;namespace NS1{
class ClassA{
public ClassA() { Console.WriteLine("constructing ClassA"); }}namespace NS2{ // a nested namespace
class ClassB{
public ClassB() { Console.WriteLine("constructing ClassB"); }}
}}class MainClass{
public static void Main(){
NS1.ClassA a = new NS1.ClassA();NS1.NS2.ClassB b = new NS1.NS2.ClassB();
}}
Using Strings in C# Programs� One of the most difficult parts of C programming is dealing with strings. Many program security holes develop from string buffer overflows, � in which programmers have used character arrays for strings, and
� hackers place more characters than memory bytes allocated for the string.
� Because many network protocols are concerned with sending and receiving text strings, it’s a good idea to get a handle on using strings properly in C# network programs.
String class� Microsoft has incorporated two string handling classes into the C# language.
� The String Class� The StringBuilder Class
� The String constructor is overloaded, providing several ways to create a string variable.
7
http://http://eembdersler.wordpress.comeembdersler.wordpress.com
C.U ElectricalC.U Electrical--Electronics Eng. 20Electronics Eng. 2011 EEE11 EEE--448448
The String Class� The basic part of string support in C# is the String class.
� The String class allows you to assign a series of characters to a variable and handle the variable in your program as a single unit.
� The String class also contains several methods that can be used to perform operations on string objects, such as determining the length of the string and comparing two strings.
The string class - IIConstructor Description
string(char[]) Creates a string from a specified character array
string(char, int) Creates a string from a specified character repeated int number of times
string(char[], int1, int2) Creates a string from a specified character array, starting at position int1 with a length of int2 bytes
string test = "This is a test string";string test2 = test;string anotherTest = new string('a', 10);
Example for stringusing System;using System.Text;
namespace ConsoleApplication10{
class Program{
static void Main(string[] args){
string test1 = "This is a test string";string test2, test3;test2 = test1.Insert(15, "application ");test3 = test1.ToUpper();Console.WriteLine("test1: '{0}'", test1);Console.WriteLine("test2: '{0}'", test2);Console.WriteLine("test3: '{0}'", test3);if (test1 == test3)
Console.WriteLine("test1 is equal to test3");else
Console.WriteLine("test1 is not equal to test3");
test2 = test1.Replace("test", "sample");Console.WriteLine("the new test2: '{0}'", test2);
}}
}
The StringBuilder Class� The StringBuilder class allows you to create and modify strings without the overhead of recreating new strings each time.
� It generates a mutable sequence of characters that can change size dynamically as the string is modified, allocating more memory as required.
StringBuilder ClassesConstructor DescriptionStringBuilder() Initializes a new default instance
with a size of 16
StringBuilder(int) Initializes a new instance with a capacity of int
StringBuilder(string) Initializes a new instance with a default value of string
StringBuilder(int1, int2) Initializes a new instance with a default capacity of int1 and a maximum capacity of int2
StringBuilder(string, int) Initializes a new instance with a default value of string and a capacity of int
StringBuilder(string, int1, int2, int3) Initializes a new instance with a default value starting at position int1of string, int2 characters long, with a capacity of int3
8
http://http://eembdersler.wordpress.comeembdersler.wordpress.com
C.U ElectricalC.U Electrical--Electronics Eng. 20Electronics Eng. 2011 EEE11 EEE--448448
StringBuilder Exampleusing System;using System.Text;namespace ConsoleApplication10{ class Program
{ static void Main(string[] args){
StringBuilder sb = new StringBuilder("test string");int length = 0;length = sb.Length;Console.WriteLine("The result is: '{0}'", sb);Console.WriteLine("The length is: {0}", length);sb.Length = 4;length = sb.Length;Console.WriteLine("The result is: '{0}'", sb);Console.WriteLine("The length is: {0}", length);sb.Length = 20;length = sb.Length;Console.WriteLine("The result is: '{0}'", sb);Console.WriteLine("The length is: {0}", length);
}}
}
StringBuilder with Appendusing System;using System.Text;
namespace ConsoleApplication1{class Program{static void Main(string[] args){StringBuilder sb = new StringBuilder();int number = 1;
sb.AppendFormat("{0}: {1} ", number++, "another string");Console.WriteLine("{0}", sb);
}}
}
ToString Exampleusing System;
class MainClass{static void Main(string[] args){int num1 = 12;float num2 = 3.05f;double num3 = 3.5;bool bl = true;
Console.WriteLine(num1.ToString());Console.WriteLine(num2.ToString());Console.WriteLine(num3.ToString());Console.WriteLine(bl.ToString());
}}
C# Streams� Data handling is one of the most important jobs of programs.
� The C# language supplies an interface to assist programmers in moving large chunks of data to and from data objects.
� The data stream allows multiple bytes of data to be transferred simultaneously to a data object so that programs can work on blocks of data instead of having to build data elements one byte at a time.
Streams- II� Streams can support three fundamental operations:� Transferring data from a stream to a memory buffer (reading)
� Transferring data from a memory buffer to a stream (writing)
� Searching the stream for a specific byte pattern (seeking)
Streams- III� The .NET System.IO namespace contains various stream classes that can be used to combine the bytes from a data source into manageable blocks that are easier to manipulate.
� The FileStream class is a good example of using a stream to simplify reading and writing data. This class provides a stream interface to easily read and write data to a disk file.
9
http://http://eembdersler.wordpress.comeembdersler.wordpress.com
C.U ElectricalC.U Electrical--Electronics Eng. 20Electronics Eng. 2011 EEE11 EEE--448448
Example for FileStreamusing System;using System.IO;
class MyStream{
private const string FILE_NAME = "Test.txt";
public static void Main(){ // Create the new, empty data file.
if (File.Exists(FILE_NAME)){ Console.WriteLine("{0} already exists!", FILE_NAME); return; }using (FileStream fs = new FileStream(FILE_NAME, FileMode.CreateNew)){ // Create the writer for data.
using (BinaryWriter w = new BinaryWriter(fs)){ /* Write data to Test.data. */ for (int i = 0; i < 11; i++) { w.Write(i); } }
}// Create the reader for data.using (FileStream fs = new FileStream(FILE_NAME, FileMode.Open,
FileAccess.Read)){
using (BinaryReader r = new BinaryReader(fs)){ /* Read data from Test.data. */ for (int i = 0; i < 11; i++) {
Console.WriteLine(r.ReadInt32()); }} } } }
C# Exception Programming� One of the biggest problems for programmers is dealing with abnormal conditions in a program.
� Inexperienced programmers often forget to compensate for error conditions such as dividing by zero.
� This results in ugly and annoying error messages and programs blowing up in customers’ faces.
� Such error conditions, or other unexpected behavior occurring when a program executes, are called exceptions.
catch -Iusing System;using System.IO;
class FinallyDemo{
static void Main(string[] args){
FileStream outStream = null;FileStream inStream = null;try {
outStream = File.OpenWrite("DestinationFile.txt");inStream = File.OpenRead("BogusInputFile.txt");
}catch (Exception ex) {
Console.WriteLine(ex.ToString());}finally {
if (outStream != null){
outStream.Close();Console.WriteLine("outStream closed.");
}if (inStream != null) {
inStream.Close();Console.WriteLine("inStream closed.");
} } }}
catch -IIusing System;class CatchError{
public static void Main(){
int var1 = 1000, var2 = 0, var3;try { var3 = var1 / var2; }catch (ArithmeticException e){
Console.WriteLine("Exception: {0}", e.ToString());var3 = -1;
}catch (Exception e){
Console.WriteLine("Exception: {0}", e.ToString());var3 = -2;
}Console.WriteLine("The result is: {0}", var3);
}}
using System;using System.Collections.Generic;using System.Text;
namespace Exception3{
class X{
int x;public X(int a) { x = a; }public int add(X o) { return x + o.x; }
}// Demonstrate NullReferenceException. public class NREDemo{
public static void Main(){
X p = new X(10);X q = null; // q is explicitly assigned null int val;try { val = p.add(q); // this will lead to an exception }catch (NullReferenceException){
Console.WriteLine("NullReferenceException!");Console.WriteLine("fixing...\n");// now, fix it q = new X(9);val = p.add(q);
}Console.WriteLine("val is {0}", val); } } }
IP Addresses in C#� One of the biggest advantages you will notice in the .NET network library is the way IP address/port pairs are handled.
� .NET defines two classes in the System.Net namespace to handle various types of IP address information:
� IPAddress� IPEndPoint
10
http://http://eembdersler.wordpress.comeembdersler.wordpress.com
C.U ElectricalC.U Electrical--Electronics Eng. 20Electronics Eng. 2011 EEE11 EEE--448448
IPAddress Methods Methods� Equals : Compares two IP addresses� GetHashCode :Returns a hash value for an IPAddress object� GetType :Returns the type of the IP address instance� HostToNetworkOrder : Converts an IP address from host byte order to network byte order
� IsLoopBack : Indicates whether the IP address is considered the loopback address
� NetworkToHostOrder : Converts an IP address from network byte order to host byte order
� Parse : Converts a string to an IPAddress instance� ToString : Converts an IPAddress to a string representation of the dotted decimal format of the IP address
� The IPAddress class also provides four read-only fields that represent special IP addresses for use in programs:
� Any :Used to represent any IP address available on the local system
� Broadcast :Used to represent the IP broadcast address for the local network
� Loopback : Used to represent the loopback address of the system
� None :Used to represent no network interface on the system
Exampleusing System;using System.Net;class AddressSample{
public static void Main (){IPAddress test1 =
IPAddress.Parse("193.140.54.10");IPAddress test2 = IPAddress.Loopback;IPAddress test3 = IPAddress.Broadcast;IPAddress test4 = IPAddress.Any;IPAddress test5 = IPAddress.None;IPHostEntry ihe =
Dns.GetHostByName(Dns.GetHostName());IPAddress myself = ihe.AddressList[0];if (IPAddress.IsLoopback(test2))
Console.WriteLine("The Loopback address is: {0}", test2.ToString());
else
Console.WriteLine("Error obtaining the loopback address");
Console.WriteLine("The Local IP address is: {0}\n", myself.ToString());
if (myself == test2)Console.WriteLine("The loopback address is the  same as local address.\n");
elseConsole.WriteLine("The loopback address is not the local address.\n");
Console.WriteLine("The test address is: {0}", test1.ToString());
Console.WriteLine("Broadcast address: {0}", test3.ToString());
Console.WriteLine("The ANY address is: {0}", test4.ToString());
Console.WriteLine("The NONE address is: {0}", test5.ToString());
}}
The results� C:\>AddressSample� The Loopback address is: 127.0.0.1� The Local IP address is: 192.168.1.6� The loopback address is not the local address.
� The test address is: 192.168.1.1� Broadcast address: 255.255.255.255� The ANY address is: 0.0.0.0� The NONE address is: 255.255.255.255
IPEndPoint� the .NET Framework uses the IPEndPointobject to represent a specific IP address/port combination.
� An IPEndPoint object is used when binding sockets to local addresses, or when connecting sockets to remote addresses.
IPEndPoint Methods � Create : Creates an EndPoint object from a SocketAddress object
� Equals : Compares two IPEndPoint objects� GetHashCode : Returns a hash value for an IPEndPoint object
� GetType :Returns the type of the IPEndPointinstance
� Serialize : Creates a SocketAddress instance of the IPEndPoint instance
� ToString : Creates a string representation of the IPEndPoint instance
11
http://http://eembdersler.wordpress.comeembdersler.wordpress.com
C.U ElectricalC.U Electrical--Electronics Eng. 20Electronics Eng. 2011 EEE11 EEE--448448
Example IPEnddPointusing System;using System.Net;class IPEndPointSample{public static void Main (){IPAddress test1 = IPAddress.Parse("192.168.1.1");IPEndPoint ie = new IPEndPoint(test1, 8000);Console.WriteLine("The IPEndPoint is: {0}", ie.ToString());Console.WriteLine("The AddressFamily is: {0}", ie.AddressFamily);Console.WriteLine("The address is: {0}, and the  port is: {1}\n", ie.Address, ie.Port);Console.WriteLine("The min port number is: {0}", IPEndPoint.MinPort);Console.WriteLine("The max port number is: {0}\n",
IPEndPoint.MaxPort);ie.Port = 80;Console.WriteLine("The changed IPEndPoint value  is: {0}", ie.ToString());SocketAddress sa = ie.Serialize();Console.WriteLine("The SocketAddress is: {0}", sa.ToString());}}
The results� C:\>IPEndPointSample� The IPEndPoint is: 192.168.1.1:8000� The AddressFamily is: InterNetwork� The address is: 192.168.1.1, and the port is: 8000� The min port number is: 0� The max port number is: 65535� The changed IPEndPoint value is: 192.168.1.1:80� The SocketAddress is: � InterNetwork:16:{0,80,192,168,1,1,0,0,0,0,0,0,0,0}
What are Sockets?� Sockets provide a common interface to the various protocols supported by networks.
� They allow you to establish connections between machines to send and receive data.
� Sockets support the simultaneous connection of multiple clients to a single server machine.
Socket Logical Structure
How do Sockets Function?� There are several modes of operation available for sockets.
� A very common mode is to establish a socket listener that listens on some port, say 4040, for connection requests.
� When a socket client, from another process or a remote computer, requests a connection on port 4040, the listener spawns a new thread that starts up a socket server on a new port, say 5051.
� From that time on the socket client and socket server communicate on port 5051. Either one can send data, in the form of a group of bytes, to the other.
� Meanwhile the listener goes back to listening for connection requests on port 4040.
Socket Client, Server, and Listener
12
http://http://eembdersler.wordpress.comeembdersler.wordpress.com
C.U ElectricalC.U Electrical--Electronics Eng. 20Electronics Eng. 2011 EEE11 EEE--448448
Client/Server Configuration
Server Main Thread
Socket Receiver Thread
Server
Socket
use socket
data
Client
Client
Socket
listener
socket
Cre
ate
Thre
ad
dataport
listener
port
Socket Data Transfer� The receiving socket, either client or server, has a buffer that stores bytes of data until the receiver thread reads them. � If the receiver buffer is full, the sender thread will block on a send call until the receiver reads some of the data out of the buffer.
� For this reason, it is a good idea to assign a thread in the receiver to empty the buffer and enqueue the data for a worker thread to digest.
� If the receiver buffer becomes full during a send, the send request will return having sent less than the requested number of bytes.
� If the receiving buffer is empty, a read request will block. � If the receiving buffer has data, but less than the number of bytes requested by a read, the call will return with the bytes available.
Non-Blocking Communication
Process #2
receiver
Process #1
sender
function sending
data to
Process #2
function receiving
data from
Process #1
interprocesscommunication
FIFO queue
processing thread
receiver thread
Basic .Net Network Objects� TCPListener
� TCPListener(port)� AcceptTcpClient()� AcceptSocket()� Start()� Stop()
� Socket� Send(byte[], size, socketFlags)� Receive(byte[], size, socketFlags)� Close()� ShutDown(SocketShutDown)
More Network Programming Objects
� TCPClient� TCPClient()� Connect(IPAddress, port)� GetStream()� Close()
� NetworkStream� NetworkStream(Socket)� Read(byte[], offset, size)� Write(byte[], offset, size)
You read and write
using the returned
NetworkStream object
Simple Socket ClientTcpClient tcpc = new TcpClient();
Byte[] read = new Byte[32]; // read buffer
String server = args[0]; // server name
// Try to connect to the server
tcpc.Connect(server, 2048);
// Get a NetworkStream object
Stream s;
s = tcpc.GetStream();
// Read the stream and convert it to ASII
int bytes = s.Read(read, 0, read.Length);
String Time = Encoding.ASCII.GetString(read);
// Display the data
Console.WriteLine("\n Received {0} bytes", bytes);
Console.WriteLine(" Current date and time is: {0}", Time);
tcpc.Close();
Connects to
server with this
name
Connects to this
server port
13
http://http://eembdersler.wordpress.comeembdersler.wordpress.com
C.U ElectricalC.U Electrical--Electronics Eng. 20Electronics Eng. 2011 EEE11 EEE--448448
Simple Socket ServerTcpListener tcpl = new TcpListener(2048); // listen on port 2048
tcpl.Start();
while (true)
{
// Accept will block until someone connects
Socket s = tcpl.AcceptSocket();
// Get current date and time then concatenate it into a string
now = DateTime.Now;
strDateLine = now.ToShortDateString()
+ " " + now.ToLongTimeString();
// Convert the string to a Byte Array and send it
Byte[] byteDateLine = ASCII.GetBytes(strDateLine.ToCharArray());
s.Send(byteDateLine, byteDateLine.Length, 0);
s.Close();
Console.WriteLine("\n Sent {0}", strDateLine);
}
What About Thread Synchronization?� Threads
� 1) is the main GUI thread that starts when you start the Server application. The thread labeled
� 2) starts whenever any client tries to connect to the socket. The thread labeled
� 3) spawns when there is any write activity by any one of the connected clients.
Multi-threaded Server� If we want to support concurrent clients, the server must spawn a thread for each new client.
� C# Thread class makes that fairly simple.� Create a class that provides a non-static processing function. This is the code that serves each client.
� Each time the TCPListener accepts a client it returns a socket. Pass that to the thread when it is constructed, and start the thread.
Define Thread’s Processingclass threadProc
{
private Socket _sock = null;
public threadProc(Socket sock)
{
_sock = sock;
}
public void proc()
{
for(int i=0; i<20; i++)
{
// Get the current date and time then concatenate it
// into a string
DateTime now = DateTime.Now;
string strDateLine = now.ToShortDateString() + " "
+ now.ToLongTimeString();
// Convert the string to a Byte Array and send it
Byte[] byteDateLine = Encoding.ASCII.GetBytes(strDateLine.ToCharArray());
_sock.Send(byteDateLine, byteDateLine.Length, 0);
Console.Write("\n Sent {0}", strDateLine);
Thread.Sleep(1000); // wait for one second just for demo
}
string QuitMessage = "Quit";
Byte[] byteQuit = Encoding.ASCII.GetBytes(QuitMessage.ToCharArray());
_sock.Send(byteQuit, byteQuit.Length, 0);
while(_sock.Connected)
Thread.Sleep(100);
_sock.Close();
}
}
14
http://http://eembdersler.wordpress.comeembdersler.wordpress.com
C.U ElectricalC.U Electrical--Electronics Eng. 20Electronics Eng. 2011 EEE11 EEE--448448
Server Spawns Threads to HandleNew Clients with threadProc.proc()
// listen on port 2048
TcpListener tcpl = new TcpListener(2048);
tcpl.Start();
while (true)
{
// Accept will block until someone connects
Socket s = tcpl.AcceptSocket();
threadProc tp = new threadProc(s);
// pass threadProc.proc() function reference to
// ThreadStart delegate
Thread t = new Thread(new ThreadStart(tp.proc));
t.Start();
}
Clients now Wait for Server to Complete// Try to connect to the server
tcpc.Connect(server, 2048);
// Get the NetworkStream object
Stream s;
s = tcpc.GetStream();
while(true)
{
// Read the stream and convert it to ASII
int bytes = s.Read(read, 0, read.Length);
String TSvrMsg = Encoding.ASCII.GetString(read);
TSrvMsg = TSrvMsg.Remove(bytes,TSrvMsg.Length-bytes);
// Display the data
if(TSrvMsg == "Quit")
{
Console.Write("\n Quitting");
break;
}
Console.WriteLine(" Server date and time is: {0}", TSrvMsg);
}
tcpc.Close();
Talk Protocol� The hardest part of a client/server socket communication design is to control the active participant
� If single-threaded client and server both talk at the same time, their socket buffers will fill up and they both will block, e.g., deadlock.
� If they both listen at the same time, again there is deadlock.
� Often the best approach is to use separate send and receive threads
� two unilateral communication channels
� The next slide shows how to safely use bilateral communication.
Bilateral Channel Talk-Listen Protocol
Each connection channel contains one “sending” token.
Message Length� Another vexing issue is that the receiver may not know how long a sent message is.
� so the receiver doesn’t know how many bytes to pull from the stream to compose a message.
� Often, the communication design will arrange to use message delimiters, fixed length messages, or message headers that carry the message length as a parameter.
Message Framing� There are three solutions to this problem:
� Use fixed length messages – rarely useful� Use fixed length message headers
� Encode message body length in header� Reader pulls header, parses to find length of rest of message and pulls it.
� Use message termination sentinals� <msg>body of message</msg>� Reader reads a character at a time out of channel� Adds character to message� Scans message from back looking for </msg> to conclude message extraction.
15
http://http://eembdersler.wordpress.comeembdersler.wordpress.com
C.U ElectricalC.U Electrical--Electronics Eng. 20Electronics Eng. 2011 EEE11 EEE--448448
They’re Everywhere� Virtually every network and internet communication method uses sockets, often in a way that is invisible to an application designer.
� Browser/server� ftp� SOAP� Network applications