Вы находитесь на странице: 1из 15

Socket Connections in C#

Sockets:

Sockets are used to interface to


networks.

Allows programs to access the


network similar to doing file I/O.

Sockets are stream!ased.

Ser"er waits #listens$ for client to


re%uest connection.

&hen client re%uest is recei"ed'


ser"er sets up o!(ects for sending
and recei"ing.

&hen terminated' ser"er returns


to listen phase.

C# pro"ides o!(ects for sockets.

Ser"er )unction:

Create an o!(ect of *cp+istener


,inds ser"er to port num!er

Call Start method


,egin connection re%uest

-ake connection !etween ser"er and


client
.eturns a Socket o!(ect

/rocessing phase
-ethods .ecei"e and Send

Connectiontermination phase
-ethod Close

Client )unction:

Create o!(ect of *cpClient

-ethod Connect

0et a 1etworkStream
&rite,2te and .ead,2te

/rocessing phase
Client and ser"er communicate

Close connection

-ethod Close

Simple Ser"er/Client
/rogram:

Start ser"er application #on


ser"er s2stem$.

Start client application #on


client s2stem$.

Client re%uests connection.

Ser"ers starts stream


communication.

3pon completion ser"er release


connection.
45ample of Ser"er Chat /rogram
using Sockets
// )ig. 66.7: Ser"er.cs
// Set up a Ser"er that will recei"e a connection from a client'
// send a string to the client' and close the connection.
using S2stem8
using S2stem.9rawing8
using S2stem.Collections8
using S2stem.Component-odel8
using S2stem.&indows.)orms8
using S2stem.*hreading8
using S2stem.1et.Sockets8
using S2stem.IO8
namespace ChatSer"er
:
// ser"er that awaits client connections #one at a time$ and
// allows a con"ersation !etween client and ser"er
pu!lic class Ser"er : S2stem.&indows.)orms.)orm
:
pri"ate S2stem.&indows.)orms.*e5t,o5 input*e5t,o58
pri"ate S2stem.&indows.)orms.*e5t,o5 displa2*e5t,o58
pri"ate Socket connection8
pri"ate *hread read*hread8
pri"ate S2stem.Component-odel.Container components ; null8
pri"ate 1etworkStream socketStream8
pri"ate ,inar2&riter writer8
pri"ate ,inar2.eader reader8

// default constructor
pu!lic Ser"er#$
:
//
// .e%uired for &indows )orm 9esigner support
//
Initiali<eComponent#$8
//
// *O9O: Add an2 constructor code after Initiali<eComponent call
//
// create a new thread from the ser"er
read*hread ; new *hread# new *hreadStart# .unSer"er $ $8
read*hread.Start#$8
=
/// >summar2?
/// Clean up an2 resources !eing used.
/// >/summar2?
protected o"erride "oid 9ispose# !ool disposing $
:
if# disposing $
:
if#components @; null$
:
components.9ispose#$8
=
=
!ase.9ispose# disposing $8
=

#region &indows )orm 9esigner generated code
/// >summar2?
/// .e%uired method for 9esigner support do not modif2
/// the contents of this method with the code editor.
/// >/summar2?
pri"ate "oid Initiali<eComponent#$
:
this.displa2*e5t,o5 ; new S2stem.&indows.)orms.*e5t,o5#$8
this.input*e5t,o5 ; new S2stem.&indows.)orms.*e5t,o5#$8
this.Suspend+a2out#$8
//
// displa2*e5t,o5
//
this.displa2*e5t,o5.+ocation ; new S2stem.9rawing./oint#A' BC$8
this.displa2*e5t,o5.-ultiline ; true8
this.displa2*e5t,o5.1ame ; Ddispla2*e5t,o5D8
this.displa2*e5t,o5..eadOnl2 ; true8
this.displa2*e5t,o5.Si<e ; new S2stem.9rawing.Si<e#6E6' 6CA$8
this.displa2*e5t,o5.*a!Inde5 ; 78
this.displa2*e5t,o5.*e5t ; DD8
//
// input*e5t,o5
//
this.input*e5t,o5.+ocation ; new S2stem.9rawing./oint#A' A$8
this.input*e5t,o5.1ame ; Dinput*e5t,o5D8
this.input*e5t,o5.Si<e ; new S2stem.9rawing.Si<e#6E6' 6C$8
this.input*e5t,o5.*a!Inde5 ; C8
this.input*e5t,o5.*e5t ; DD8
this.input*e5t,o5.Fe29own G; new S2stem.&indows.)orms.Fe24"entHandler#this.input*e5t,o5IFe29own$8

//
// Ser"er
//
this.AutoScale,aseSi<e ; new S2stem.9rawing.Si<e#J' 7K$8
this.ClientSi<e ; new S2stem.9rawing.Si<e#6L6' 6M7$8
this.Controls.Add.ange#new S2stem.&indows.)orms.ControlNO :
this.displa2*e5t,o5'
this.input*e5t,o5=$8
this.1ame ; DSer"erD8
this.*e5t ; DSer"erD8
this.Closing G; new S2stem.Component-odel.Cancel4"entHandler#this.Ser"erIClosing$8
this..esume+a2out#false$8
=
#endregion
NS*A*hreadO
static "oid -ain#$
:
Application..un# new Ser"er#$ $8
=
protected "oid Ser"erIClosing#
o!(ect sender' Cancel4"entArgs e $
:
S2stem.4n"ironment.45it# S2stem.4n"ironment.45itCode $8
=

// sends the te5t t2ped at the ser"er to the client
protected "oid input*e5t,o5IFe29own#
o!(ect sender' Fe24"entArgs e $
:
// sends the te5t to the client
tr2
:
if # e.Fe2Code ;; Fe2s.4nter PP connection @; null $
:
writer.&rite# DS4.Q4.??? D G input*e5t,o5.*e5t $8

displa2*e5t,o5.*e5t G;
DRrRnS4.Q4.??? D G input*e5t,o5.*e5t8
// if the user at the ser"er signaled termination
// se"er the connection to the client
if # input*e5t,o5.*e5t ;; D*4.-I1A*4D $
connection.Close#$8
input*e5t,o5.Clear#$8
=
=
catch # Socket45ception $
:
displa2*e5t,o5.*e5t G; DRn4rror writing o!(ectD8
=
=
// allows a client to connect and displa2s the te5t it sends
pu!lic "oid .unSer"er#$
:
*cp+istener listener8
int counter ; 78

// wait for a client connection and displa2 the te5t
// that the client sends
tr2
:
// Step 7: create *cp+istener
listener ; new *cp+istener# JCCC $8
// Step 6: *cp+istener waits for connection re%uest
listener.Start#$8
// Step K: esta!lish connection upon client re%uest
while # true $
:
displa2*e5t,o5.*e5t ; D&aiting for connectionRrRnD8
// accept an incoming connection
connection ; listener.AcceptSocket#$8
// create 1etworkStream o!(ect associated with socket
socketStream ; new 1etworkStream# connection $8
// create o!(ects for transferring data across stream
writer ; new ,inar2&riter# socketStream $8
reader ; new ,inar2.eader# socketStream $8
displa2*e5t,o5.*e5t G; DConnection D G counter G
D recei"ed.RrRnD8

// inform client that connection was successfull
writer.&rite# DS4.Q4.??? Connection successfulD $8
input*e5t,o5..eadOnl2 ; false8
string the.epl2 ; DD8
// Step B: read String data sent from client
do
:
tr2
:
// read the string sent to the ser"er
the.epl2 ; reader..eadString#$8
// displa2 the message
displa2*e5t,o5.*e5t G; DRrRnD G the.epl28
=

// handle e5ception if error reading data
catch # 45ception $
:
!reak8
=
= while # the.epl2 @; DC+I41*??? *4.-I1A*4D PP
connection.Connected $8
displa2*e5t,o5.*e5t G;
DRrRn3ser terminated connectionD8
// Step J: close connection
input*e5t,o5..eadOnl2 ; true8
writer.Close#$8
reader.Close#$8
socketStream.Close#$8
connection.Close#$8
GGcounter8
=
= // end tr2
catch # 45ception error $
:
-essage,o5.Show# error.*oString#$ $8
=
= // end method .unSer"er
= // end class Ser"er
=

Вам также может понравиться