Sie sind auf Seite 1von 16

Programming_Network

Csharp
Mohamed Khatiri 1988

Year : 2010
3 rd Computer Science
Mido-kok@hotmail.fr
Socket connection
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;

class MainClass
{
public static void Main()
{
IPAddress host = IPAddress.Parse("192.168.1.1");
IPEndPoint hostep = new IPEndPoint(host, 8000);
Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Strea
m, ProtocolType.Tcp);

try
{
sock.Connect(hostep);
sock.Send(Encoding.ASCII.GetBytes("testing"));

} catch (SocketException e) {
Console.WriteLine("Problem connecting to host");
Console.WriteLine(e.ToString());
sock.Close();
return;
}

sock.Close();
}
}

2
Listen for Socket Request in Thread

using System;
using System.Text;
using System.Threading;
using System.Net;
using System.Net.Sockets;

public class MainClass {

static void ListenForRequests() {


int CONNECT_QUEUE_LENGTH = 4;

Socket listenSock = new Socket( AddressFamily.InterNetwork, SocketT


ype.Stream, ProtocolType.Tcp );
listenSock.Bind( new IPEndPoint(IPAddress.Any,9999) );
listenSock.Listen( CONNECT_QUEUE_LENGTH );

while( true ) {
using( Socket newConnection = listenSock.Accept() ) {
// Send the data.
byte[] msg = Encoding.UTF8.GetBytes( "Hello World!" );
newConnection.Send( msg, SocketFlags.None );
}
}
}

static void Main() {


// Start the listening thread.
Thread listener = new Thread(new ThreadStart(ListenForRequests) );
listener.IsBackground = true;
listener.Start();

Console.WriteLine( "Press <enter> to quit" );


Console.ReadLine();
}
}

3
Simple Tcp server: receive data from a client
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;

class MainClass
{
public static void Main()
{
IPEndPoint ip = new IPEndPoint(IPAddress.Any,9999);
Socket socket = new Socket(AddressFamily.InterNetwork,SocketType.Stream,
ProtocolType.Tcp);

socket.Bind(ip);
socket.Listen(10);
Console.WriteLine("Waiting for a client...");
Socket client = socket.Accept();
IPEndPoint clientep =(IPEndPoint)client.RemoteEndPoint;
Console.WriteLine("Connected with {0} at port {1}",clientep.Address ,
clientep.Port);

string welcome = "Welcome";


byte[] data = new byte[1024];
data = Encoding.ASCII.GetBytes(welcome);
client.Send(data, data.Length,SocketFlags.None);

while(true)
{
data = new byte[1024];
int receivedDataLength = client.Receive(data);
Console.WriteLine(Encoding.ASCII.GetString(data, 0, receivedDataLength));
client.Send(data, receivedDataLength, SocketFlags.None);
}

Console.WriteLine("Disconnected from {0}",clientep.Address);


client.Close();
socket.Close();
}
}

4
Simple Tcp server: send data to the client
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;

class MainClass
{
public static void Main()
{
IPEndPoint ip = new IPEndPoint(IPAddress.Any,9999);
Socket socket = new Socket(AddressFamily.InterNetwork,SocketType.Stre
am, ProtocolType.Tcp);

socket.Bind(ip);
socket.Listen(10);
Console.WriteLine("Waiting for a client...");
Socket client = socket.Accept();
IPEndPoint clientep =(IPEndPoint)client.RemoteEndPoint;
Console.WriteLine("Connected with {0} at port {1}",clientep.Address,
clientep.Port);

string welcome = "Welcome";


byte[] data = new byte[1024];
data = Encoding.ASCII.GetBytes(welcome);
client.Send(data, data.Length,SocketFlags.None);

Console.WriteLine("Disconnected from {0}",clientep.Address);


client.Close();
socket.Close();
}
}

5
Simple Tcp Client: send data to the server
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;

class MainClass
{
public static void Main()
{
IPEndPoint ip = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9999);

Socket server = new Socket(AddressFamily.InterNetwork,SocketType.Stre


am, ProtocolType.Tcp);

try
{
server.Connect(ip);
} catch (SocketException e){
Console.WriteLine("Unable to connect to server.");
return;
}

Console.WriteLine("Type 'exit' to exit.");


while(true)
{
string input = Console.ReadLine();
if (input == "exit")
break;
server.Send(Encoding.ASCII.GetBytes(input));
byte[] data = new byte[1024];
int receivedDataLength = server.Receive(data);
string stringData = Encoding.ASCII.GetString(data, 0, receivedData
Length);
Console.WriteLine(stringData);
}

server.Shutdown(SocketShutdown.Both);
server.Close();
}
}

6
Simple Tcp Client: receive data from server
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;

class MainClass
{
public static void Main()
{
IPEndPoint ip = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9999);

Socket server = new Socket(AddressFamily.InterNetwork,SocketType.Stre


am, ProtocolType.Tcp);

try
{
server.Connect(ip);
} catch (SocketException e){
Console.WriteLine("Unable to connect to server.");
return;
}

byte[] data = new byte[1024];


int receivedDataLength = server.Receive(data);
string stringData = Encoding.ASCII.GetString(data, 0, receivedDataLen
gth);
Console.WriteLine(stringData);

server.Shutdown(SocketShutdown.Both);
server.Close();
}
}

7
Simple Udp Client: send and receive

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;

class MainClass
{
public static void Main()
{
byte[] data = new byte[1024];
string input, stringData;
IPEndPoint ip = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9999);

Socket server = new Socket(AddressFamily.InterNetwork,SocketType.Dgram,


ProtocolType.Udp);

string welcome = "Hello";


data = Encoding.ASCII.GetBytes(welcome);
server.SendTo(data, data.Length, SocketFlags.None, ip);

IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);


EndPoint Remote = (EndPoint)sender;

data = new byte[1024];


int receivedDataLength = server.ReceiveFrom(data, ref Remote);

Console.WriteLine("Message received from {0}:", Remote.ToString());


Console.WriteLine(Encoding.ASCII.GetString(data, 0,receivedDataLength));

server.Close();
}
}

8
Simple Udp server
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;

class MainClass
{
public static void Main()
{
int receivedDataLength;
byte[] data = new byte[1024];
IPEndPoint ip = new IPEndPoint(IPAddress.Any, 9999);

Socket socket = new Socket(AddressFamily.InterNetwork,SocketType.Dgram,


ProtocolType.Udp);

socket.Bind(ip);

IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);


EndPoint Remote = (EndPoint)(sender);

while(true)
{
data = new byte[1024];
receivedDataLength = socket.ReceiveFrom(data, ref Remote);

Console.WriteLine(Encoding.ASCII.GetString(data, 0, receivedDataLength));
socket.SendTo(data, receivedDataLength, SocketFlags.None, Remote);
}

}
}

9
Create a NetworkStream from a Socket
using System;
using System.IO;
using System.Net.Sockets ;

class MainClass
{
public static void Main()
{
TcpListener tcpl = new TcpListener(9999);
tcpl.Start();

for (;;)
{
Socket newSocket = tcpl.AcceptSocket();
if (newSocket.Connected)
{
NetworkStream ns = new NetworkStream(newSocket);

byte[] buf = {1,2,3,4,5,6,7,8,9};


ns.Write(buf, 0, 9);

ns.Flush();
ns.Close();

}
newSocket.Close();
break;

}
}

10
NetworkStream TcpClient
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;

class MainClass
{
public static void Main()
{
IPEndPoint ip = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9999);

Socket server = new Socket(AddressFamily.InterNetwork,SocketType.Stream,


ProtocolType.Tcp);

try
{
server.Connect(ip);
} catch (SocketException e){
Console.WriteLine(e.ToString());
return;
}

NetworkStream ns = new NetworkStream(server);

if (ns.CanRead){
byte[] data = new byte[1024];
int receivedDataLength = ns.Read(data, 0, data.Length);
string stringData = Encoding.ASCII.GetString(data, 0, receivedDataLength);
Console.WriteLine(stringData);
}else{
Console.WriteLine("Error: Can't read from this socket");
}

ns.Close();
server.Shutdown(SocketShutdown.Both);
server.Close();
}
}

11
Network Streaming Server
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;

public class NetworkIOServer


{
public static void Main()
{
IPAddress localAddr = IPAddress.Parse( "127.0.0.1" );
TcpListener tcpListener = new TcpListener( localAddr, 65000 );
tcpListener.Start();

for ( ; ; )
{
Socket socketForClient = tcpListener.AcceptSocket();
SendFileToClient( socketForClient );
socketForClient.Close();
break;
}
}

static void SendFileToClient(Socket socketForClient )


{
NetworkStream networkStream = new NetworkStream( socketForClient );
System.IO.StreamWriter streamWriter = new System.IO.StreamWriter
( networkStream );
System.IO.StreamReader streamReader = new System.IO.StreamReader
("myTest.txt" );
string theString;
do
{
theString = streamReader.ReadLine();
if ( theString != null )
{
Console.WriteLine("Sending {0}", theString );
streamWriter.WriteLine( theString );
streamWriter.Flush();
}
}
while ( theString != null );
streamReader.Close();
networkStream.Close();
streamWriter.Close();
}
}

12
Network Streaming Client
using System;
using System.Collections.Generic;
using System.Net.Sockets;
using System.Text;

public class Client


{
static public void Main( string[] Args )
{
TcpClient socketForServer = new TcpClient( "localHost", 65000 );
NetworkStream networkStream = socketForServer.GetStream();
System.IO.StreamReader streamReader = new System.IO.StreamReader
( networkStream );
string outputString;
do{
outputString = streamReader.ReadLine();

if ( outputString != null )
{
Console.WriteLine( outputString );
}
}while ( outputString != null );
networkStream.Close();
}
}

13
Use NetworkStream to read and write to a server
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;

class MainClass
{
public static void Main()
{
IPEndPoint ip = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9999);

Socket server = new Socket(AddressFamily.InterNetwork,SocketType.Stream,


ProtocolType.Tcp);

try
{
server.Connect(ip);
} catch (SocketException e){
Console.WriteLine(e.ToString());
return;
}

NetworkStream ns = new NetworkStream(server);

while(true)
{
byte[] data = new byte[1024];
string input = Console.ReadLine();
if (ns.CanWrite){
ns.Write(Encoding.ASCII.GetBytes(input), 0, input.Length);
ns.Flush();
}

int receivedDataLength = ns.Read(data, 0, data.Length);


string stringData = Encoding.ASCII.GetString(data, 0, receivedDataLength);
Console.WriteLine(stringData);
}

ns.Close();
server.Shutdown(SocketShutdown.Both);
server.Close();
}
}

14
Create NetworkStream from TcpClient
using System;
using System.IO;
using System.Net.Sockets ;

class MainClass
{
public static void Main()
{
TcpClient newSocket = new TcpClient("localhost", 50001);

NetworkStream ns = newSocket.GetStream();

byte[] buf = new byte[100];


ns.Read(buf, 0, 100);

char[] buf2 = new char[100];


for(int i=0;i<100;i++)
buf2[i]=(char)buf[i];
Console.WriteLine(buf2);

ns.Close();
newSocket.Close();

15
TcpListener Sample
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;

class MainClass
{
public static void Main()
{
int receivedDataLength;
byte[] data = new byte[1024];

TcpListener socket = new TcpListener(9999);


socket.Start();

TcpClient client = socket.AcceptTcpClient();


NetworkStream ns = client.GetStream();

string welcome = "Welcome";


data = Encoding.ASCII.GetBytes(welcome);
ns.Write(data, 0, data.Length);

while(true)
{
data = new byte[1024];
receivedDataLength = ns.Read(data, 0, data.Length);
Console.WriteLine(Encoding.ASCII.GetString(data, 0, receivedDataLength));
ns.Write(data, 0, receivedDataLength);
}
ns.Close();
client.Close();
socket.Stop();
}
}

16