background image

© 2008 dr inż.. Sławomir Jeżewski 

Katedra Informatyki Stosowanej PŁ

Programowanie Sieciowe

Wykład z Programowania Sieciowego 

Zagadnienia sieciowe w C#

background image

© 2008 dr inż.. Sławomir Jeżewski 

Katedra Informatyki Stosowanej PŁ

Programowanie Sieciowe

Common Language Runtime (CLR)

• Microsoft .NET technology 
• Common Language Runtime (CLR) 

environment

background image

© 2008 dr inż.. Sławomir Jeżewski 

Katedra Informatyki Stosowanej PŁ

Programowanie Sieciowe

C# Namespaces

• With all of the classes 

provided in the .NET 

Framework, it’s easy to get 

confused about which classes 

perform

• which functions and the 

methods that should be used 

from particular classes. To 

help simplify things, Microsoft

• uses namespaces in 

classifying .NET Framework 

classes.

• As shown in the SampleClass 

program, each C# application 

consists of one or more 

classes. Each class

• defines an object that can 

contain data and methods to 

manipulate the data. At least 

one class in each

• application must contain a 

program interface method 

called Main(). The Main() 

method lets the C# compiler

• know where to begin 

execution of the program. 

Other classes can be defined 

within the program (such as 

the

• DataClass), or can even be 

shared with other programs.

background image

© 2008 dr inż.. Sławomir Jeżewski 

Katedra Informatyki Stosowanej PŁ

Programowanie Sieciowe

System namespaces

Namespace

 

Description of 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.Data

 Defines the ADO.NET database structure 

System.Data.OleDb

 Encapsulates the OLE DB .NET database structure

System.Drawing

 Provides access to basic graphics functionality 

System.IO

 Allows reading and writing on data streams and files

System.Net

 Provides access to the Windows network functions

System.Net.Sockets

 Provides access to the Windows sockets (Winsock) interface

System.Runtime.Remotin
g

 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

 Enables browser and web server functionality 

System.Web.Mail

 Enables sending mail messages

System.XML

 Provides support for processing XML documents

background image

© 2008 dr inż.. Sławomir Jeżewski 

Katedra Informatyki Stosowanej PŁ

Programowanie Sieciowe

System namespaces

• Data handling is one of the 

most important jobs of 

programs. There are many 

methods for storing and 

retrieving

• data in the C# world—files, 

memory, input/output devices, 

interprocess communication 

pipes, and networks.

• There are also many ways of 

reading data to and writing it 

from objects. Most objects allow 

data to be read or

• written on a byte-by-byte basis. 

This method transfers one byte 

of data into or out of the data 

object at a time.

• Certainly this works, but it is not 

the most efficient manner of 

handling data.

• 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)

background image

© 2008 dr inż.. Sławomir Jeżewski 

Katedra Informatyki Stosowanej PŁ

Programowanie Sieciowe

Wykorzystanie strumieni

1. class TestLog
2. {
3.  public static void Main ()
4.  {
5.    string lFile = "LOG.TXT";
6.  FileStream fs = new FileStream(

lFile, FileMode.OpenOrCreate, FileAccess.Write );

7.    StreamWriter sw = new StreamWriter(fs);
8.    StreamReader sr = new StreamReader(fs);
9.    sw.WriteLine(„T entry");
10.    sw.WriteLine(„T2 entry");
11.    while(sr.Peek() > -1)
12.     {
13.      Console.WriteLine(sr.ReadLine());
14.     }
15.    sw.Close();
16.    sr.Close();
17.    fs.Close();
18.  }
19. }

background image

© 2008 dr inż.. Sławomir Jeżewski 

Katedra Informatyki Stosowanej PŁ

Programowanie Sieciowe

The Unix operating system revolutionized many features in the programming world. 

Among these is the file

descriptor. A file descriptor provides a programming interface to a file object. 

Because nearly every object

contained in a Unix system is defined as a file, the file descriptor can be used to send 

and receive data

that has many objects across the Unix system. This makes life much simpler for Unix 

programmers. The

same type of programming model works no matter what type of device (or file) you 

are trying to access.

Starting in the 4.2BSD Unix release, network access was also defined using file 

descriptors. A network file

descriptor is called a socket. Unix (and Windows) network programs both utilize 

sockets for all network

communication. This section describes the features of socket network programming 

in general so that you

will be better prepared to understand the concepts behind C# network programming. 

Following this is the

“Socket Programming in Windows” section, which describes the Windows Winsock 

implementation of

sockets. Winsock is the base on which the C# Socket class implementation is built.

background image

© 2008 dr inż.. Sławomir Jeżewski 

Katedra Informatyki Stosowanej PŁ

Programowanie Sieciowe

IPAddress

Metody

background image

© 2008 dr inż.. Sławomir Jeżewski 

Katedra Informatyki Stosowanej PŁ

Programowanie Sieciowe

IPAdress

background image

© 2008 dr inż.. Sławomir Jeżewski 

Katedra Informatyki Stosowanej PŁ

Programowanie Sieciowe

IPEndpoint

• struktura Adres/Port
• Odpowiednik struktury sockaddr_in

• Konstruktory:
• IPEndPoint(long address, int port)
• IPEndPoint(IPAddress address, int port)

•  SocketAddress – wersja IPEndpoint dostosowana do 

serializacji

1. using System;
2. using System.Net;
3. class IPEndPointSample
4. {
5.   public static void Main ()
6.    {
7.      IPAddress test1 = IPAddress.Parse("192.168.2.1");
8.      IPEndPoint ie = new IPEndPoint(test1, 5000);
9.    }
10. }

background image

© 2008 dr inż.. Sławomir Jeżewski 

Katedra Informatyki Stosowanej PŁ

Programowanie Sieciowe

IPEndpoint

Properties

• Adress

• AdressFamily

• Port
Fields

• MaxPort

• MinPort

1. using System;
2. using System.Net;
3. class IPEndPointSample
4. {
5.   public static void Main ()
6.    {
7.      IPAddress test1 = IPAddress.Parse("192.168.2.1");
8.      IPEndPoint ie = new IPEndPoint(test1, 5000);
9.    }
10. }

background image

© 2008 dr inż.. Sławomir Jeżewski 

Katedra Informatyki Stosowanej PŁ

Programowanie Sieciowe

System.Net.Sockets

 

Klasa

Opis

IPv6MulticastOption 

Zawiera wartości opcji używanych przy grupach rozgłoszeniowych IPv6

IrDAClient 

Tworzy i obsługuje połączenie za pomocą podczerwieni od strony klienta.

IrDADeviceInfo 

Dostarcza informacji na temat urządzenia zdalnego połączonego za pomocą łącza podczerwiennego

IrDAListener 

Tworzy i obsługuje gniazdo serwera do połączeń za pomocą podczerwieni

LingerOption 

Specifies whether a Socket will remain connected after a call to Close and the length of time it will 
remain connected, if data remains to be sent.

MulticastOption 

Zawiera wartości typu IPAddress służące do dołączania lub odłączania się od grup rozgłoszeniowych

NetworkStream 

Klasa strumienia dostosowana do operacji na gnieździe

SendPacketsElement 

Klasa składowa tablicy SendPacketsElements .

Socket 

Implementuje interfejs Berkeley sockete.

SocketAsyncEventArgs 

Asynchroniczne operowanie na klasie socket ( połączeniu )

SocketException 

Klasa wyjątku związanego z operacjami sieciowymi.

TcpClient 

Tworzy i obsłguje generyczne połączenie TCP od strony klienta 

TcpListener 

Tworzy i obsługuje generyczne połączenie TCP od strony serwera

UdpClient 

Tworzy i obsługuje generyczne połączenie UDP

background image

© 2008 dr inż.. Sławomir Jeżewski 

Katedra Informatyki Stosowanej PŁ

Programowanie Sieciowe

Konstruktor Socket

1. using System;
2. using System.Net;
3. using System.Net.Sockets;
4. class SockProp
5. {
6. public static void Main ()
7. {
8.    IPAddress ia = IPAddress.Parse("127.0.0.1");
9.    IPEndPoint ie = new IPEndPoint(ia, 8000);
10.    Socket test = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
11.    test.Bind(ie);
12.    test.Close();
13. }
14. }

Nazwa konstruktora

Socket(SocketInformation

) 

Socket(AddressFamily, SocketTypeProtocolType

) 

background image

© 2008 dr inż.. Sławomir Jeżewski 

Katedra Informatyki Stosowanej PŁ

Programowanie Sieciowe

Klasa Socket metody podstawowe

• Metody 

implementujące 
system Berkeley 
Socket

• Metody wynikające z 

Net Framework i 
dziedziczenia po Object

 Nazwa

Nazwa

Close

DuplicateAndClose

 

Disconnect

 

Equals 

Shutdown

Finalize

Bind

 

GetHashCode

Listen

Dispose

 

Accept

GetType

Connect

MemberwiseClone

Send

 

ToString 

SendFile
SendTo

 

IOControl

 

Receive
ReceiveFrom

 

ReceiveMessageFrom
Poll

 

Select

 

SetSocketOption
GetSocketOption

1. IPHostEntry local = Dns.GetHostByName(Dns.GetHostName());

2. IPEndPoint iep = new 

IPEndPoint(local.AddressList[0], 8000);

3. Socket newserver = new 

Socket(AddressFamily.InterNetwork,

4. SocketType.Stream, ProtocolType.Tcp);
5. newserver.Bind(iep);
6. newserver.Listen(5);
7. Socket newclient = newserver.Accept();

background image

© 2008 dr inż.. Sławomir Jeżewski 

Katedra Informatyki Stosowanej PŁ

Programowanie Sieciowe

Klasa Socket metody podstawowe

• Metody 

implementujące 
system Berkeley 
Socket

• Metody wynikające z 

Net Framework i 
dziedziczenia po Object

 Nazwa

Nazwa

Close

DuplicateAndClose 

Disconnect 

Equals 

Shutdown

Finalize

Bind

 

GetHashCode

Listen

Dispose

 

Accept

GetType

Connect

MemberwiseClone

Send

 

ToString 

SendFile
SendTo

 

IOControl

 

Receive
ReceiveFrom

 

ReceiveMessageFrom
Poll

 

Select

 

SetSocketOption
GetSocketOption

1. ArrayList socketList = new ArrayList(5);
2. SocketList.Add(sock1);
3. SocketList.Add(sock2);
4. Socket.Select(socketList, null, null, 1000);
5. byte[] buffer = new byte[1024];
6. for (i = 0; i < socketList.Length - 1; i++)
7. {
8. socketList[i].Receive(buffer);
9. ConsoleWriteLine(Encoding.ASCII.GetString(buffer));
10. }

background image

© 2008 dr inż.. Sławomir Jeżewski 

Katedra Informatyki Stosowanej PŁ

Programowanie Sieciowe

Socket metody asynchroniczne

Funkcja inicjująca

Funkcja kończąca

BeginAccept

 

EndAccept

 

BeginConnect

 

EndConnect

 

BeginDisconnect

 

EndDisconnect

 

BeginReceive

 

EndReceive

 

BeginReceiveFrom

 

EndReceiveFrom

BeginReceiveMessageFro
m

 

EndReceiveMessageFrom

BeginSend

 

EndSend

BeginSendFile

 

EndSendFile

BeginSendTo

 

EndSendTo

background image

© 2008 dr inż.. Sławomir Jeżewski 

Katedra Informatyki Stosowanej PŁ

Programowanie Sieciowe

TCP Client

• Klasa pomocnicza automatyzująca tworzenie 

gniazda klienckiego

TcpClient newclient = new TcpClient();
newclient.Connect("www.isp.net", 8000);

TcpClient newclient = new TcpClient("www.isp.net", 8000);
NetworkStream ns = newclient.GetStream();
byte[] outbytes = Encoding.ASCII.GetBytes("Testing");
ns.Write(outbytes, 0, outbytes.Length);
byte[] inbytes = new byte[1024];
ns.Read(inbytes, 0, inbytes.Length);
string instring = Encoding.ASCII.GetString(inbytes);
Console.WriteLine(instring);
ns.Close();
newclient.Close();

background image

© 2008 dr inż.. Sławomir Jeżewski 

Katedra Informatyki Stosowanej PŁ

Programowanie Sieciowe

TCPListener

• Klasa pomocnicza automatyzująca tworzenie 

połączenia nasłuchującego

TcpListener nserver = new TcpListener(9050);
newserver.Start();
TcpClient nclient = nserver.AcceptTcpClient();
NetworkStream ns = nclient.GetStream();
byte[] ob = Encoding.ASCII.GetBytes("Testing");
ns.Write(ob, 0, ob.Length);
byte[] ib = new byte[1025];
ns.Read(ib, 0, ib.Length);
string instring = Encoding.ASCII.GetString(ib);

ns.Close();
nclient.Close();
nserver.Stop();

background image

© 2008 dr inż.. Sławomir Jeżewski 

Katedra Informatyki Stosowanej PŁ

Programowanie Sieciowe

UdpClient

• Klasa pomocnicza automatyzująca 

tworzenie gniazda UDP

UdpClient nc = new UdpClient(8000);
IPEndPoint rclient = new IPEndPoint(IPAddress.Any, 0);
byte[] recv = newconn.Receive(ref rclient);
string data = Encoding.ASCII.GetString(recv);
ConsoleWriteLine("From: {0}", remoteclient.ToString());

newconn.Close();


Document Outline