天天看點

C# Socket程式設計

一、同步方式:

1.伺服器端 server.cs

using system;

using system.net.sockets;

using system.net;

using system.io;

class progserveur

{

static readonly ushort port = 50000;

static void main()

ipaddress ipaddress = new ipaddress( new byte[] { 127, 0, 0, 1 } );

tcplistener tcplistener = new tcplistener( ipaddress , port );

tcplistener.start();

// each loop = send a file to a client.

while(true)

try

console.writeline( "waiting for a client..." );

// ‘accepttcpclient()’ is a blocking call. the thread

// continue its course only when a client is connected.

tcpclient tcpclient = tcplistener.accepttcpclient();

console.writeline( "用戶端與伺服器連結成功!" );

processclientrequest( tcpclient.getstream() );

console.writeline( "用戶端與伺服器斷開連結!" );

}

catch( exception e )

console.writeline( e.message );

static void processclientrequest( networkstream networkstream )

// stream used to send data.

streamwriter streamwriter = new streamwriter( networkstream );

// stream used to read the file.

streamreader streamreader = new streamreader( @"c:/text/file.txt" );

// for each line of the file: send it to the client.

string stmp = streamreader.readline();

try {

while(stmp != null ) {

console.writeline( "sending: {0}" , stmp );

streamwriter.writeline( stmp );

streamwriter.flush();

stmp = streamreader.readline();

finally {

// close streams.

streamreader.close();

streamwriter.close();

networkstream.close();

2.用戶端 client.cs

 using system;

class progclient {

static readonly string host = "localhost";

static void main() {

tcpclient tcpclient;

// invoking the ‘tcpclient’ constructor raises an exception

// if it can’t connect to the server.

tcpclient = new tcpclient( host , port );

console.writeline("連接配接到的伺服器ip位址:{0},端口号:{1}",host,port);

networkstream networkstream = tcpclient.getstream();

streamreader streamreader = new streamreader( networkstream );

// each loop = a line is fetched from the server.

while( stmp != null ) {

console.writeline( "receiving: {0}" , stmp );

// close stream.

console.writeline( "斷開的伺服器ip位址:{0},端口:{1}", host, port);

console.read();

catch( exception e ) {

return;

二、異步方式

 1.伺服器端 server.cs

using system.text;

class progserveur {

tcplistener tcplistener = new tcplistener( ipaddress, port );

while(true) {

console.writeline( "main:waiting for a client..." );

console.writeline( "main:client connected." );

clientrequestprocessing clientrequestprocessing =

new clientrequestprocessing( tcpclient.getstream() );

clientrequestprocessing.go();

// an instance of this class is created for each client.

class clientrequestprocessing {

static readonly int buffersize = 512;

private byte [] m_buffer;

private networkstream m_networkstream;

private asynccallback m_callbackread;

private asynccallback m_callbackwrite;

// the constructor initializes :

// - m_networkstream: stream to communicate with the client.

// - m_callbackread : callback procedure for read.

// - m_callbackwrite: callback procedure for write.

// - m_buffer : used both for reading and writing data.

public clientrequestprocessing( networkstream networkstream ) {

m_networkstream = networkstream;

m_callbackread = new asynccallback( this.onreaddone );

m_callbackwrite = new asynccallback( this.onwritedone );

m_buffer = new byte[ buffersize ];

public void go() {

m_networkstream.beginread(

m_buffer, 0 , m_buffer.length , m_callbackread , null );

// this callback procedure is called when an asynchronous read

// triggered by a call to ‘beginread()’ terminates.

private void onreaddone( iasyncresult asyncresult ) {

int nbytes = m_networkstream.endread(asyncresult );

// send back the received string to the client.

if( nbytes > 0 ){

string s = encoding.ascii.getstring( m_buffer , 0 , nbytes );

console.write(

"async:{0} bytes received from client: {1}" , nbytes, s );

m_networkstream.beginwrite(

m_buffer, 0 , nbytes , m_callbackwrite , null );

// if the client didn’t send anything, the we discard him.

else{

console.writeline( "async:client request processed." );

m_networkstream.close();

m_networkstream = null;

// this callback procedure is called when an asynchronous write

// triggered by a call to ‘beginwrite()’ terminates.

private void onwritedone( iasyncresult asyncresult ) {

m_networkstream.endwrite( asyncresult );

console.writeline( "async:write done." );

try{

tcpclient = new tcpclient(host,port);

console.writeline("connection established with {0}:{1}",host,port);

// initialize the stream to communicate with the server

// available for sending and receiving data.

streamwriter streamwriter =new streamwriter( networkstream );

streamreader streamreader =new streamreader( networkstream );

string ssend = "hi from the client!";

string sreceived;

for(int i=0;i<3;i++) {

// send data to the server.

console.writeline( "client -> server :" + ssend );

streamwriter.writeline( ssend );

// receiving data from the server.

sreceived = streamreader.readline();

console.writeline( "server -> client :" + sreceived );

finally{

catch(exception e) {