/*
C# Network Programming
by Richard Blum
Publisher: Sybex
ISBN: 0782141765
*/
using System;
using System.Collections;
using System.Net;
using System.Net.Sockets;
using System.Text;
public class SelectTcpSrvr
{
public static void Main()
{
ArrayList sockList = new ArrayList(2);
ArrayList copyList = new ArrayList(2);
Socket main = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
IPEndPoint iep = new IPEndPoint(IPAddress.Any, 9050);
byte[] data = new byte[1024];
string stringData;
int recv;
main.Bind(iep);
main.Listen(2);
Console.WriteLine("Waiting for 2 clients...");
Socket client1 = main.Accept();
IPEndPoint iep1 = (IPEndPoint)client1.RemoteEndPoint;
client1.Send(Encoding.ASCII.GetBytes("Welcome to the server"));
Console.WriteLine("Connected to {0}", iep1.ToString());
sockList.Add(client1);
Console.WriteLine("Waiting for 1 more client...");
Socket client2 = main.Accept();
IPEndPoint iep2 = (IPEndPoint)client2.RemoteEndPoint;
Console.WriteLine("Connected to {0}", iep2.ToString());
client2.Send(Encoding.ASCII.GetBytes("Welcome to the server"));
sockList.Add(client2);
main.Close();
while(true)
{
copyList = new ArrayList(sockList);
Console.WriteLine("Monitoring {0} sockets...", copyList.Count);
Socket.Select(copyList, null, null, 10000000);
foreach(Socket client in copyList)
{
data = new byte[1024];
recv = client.Receive(data);
stringData = Encoding.ASCII.GetString(data, 0, recv);
Console.WriteLine("Received: {0}", stringData);
if (recv == 0)
{
iep = (IPEndPoint)client.RemoteEndPoint;
Console.WriteLine("Client {0} disconnected.", iep.ToString());
client.Close();
sockList.Remove(client);
if (sockList.Count == 0)
{
Console.WriteLine("Last client disconnected, bye");
return;
}
}
else
client.Send(data, recv, SocketFlags.None);
}
}
}
}
Month: February 2011
Async Tcp Server
/*
C# Network Programming
by Richard Blum
Publisher: Sybex
ISBN: 0782141765
*/
using System;
using System.Drawing;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Windows.Forms;
public class AsyncTcpSrvr : Form
{
private TextBox conStatus;
private ListBox results;
private byte[] data = new byte[1024];
private int size = 1024;
private Socket server;
public AsyncTcpSrvr()
{
Text = "Asynchronous TCP Server";
Size = new Size(400, 380);
results = new ListBox();
results.Parent = this;
results.Location = new Point(10, 65);
results.Size = new Size(350, 20 * Font.Height);
Label label1 = new Label();
label1.Parent = this;
label1.Text = "Text received from client:";
label1.AutoSize = true;
label1.Location = new Point(10, 45);
Label label2 = new Label();
label2.Parent = this;
label2.Text = "Connection Status:";
label2.AutoSize = true;
label2.Location = new Point(10, 330);
conStatus = new TextBox();
conStatus.Parent = this;
conStatus.Text = "Waiting for client...";
conStatus.Size = new Size(200, 2 * Font.Height);
conStatus.Location = new Point(110, 325);
Button stopServer = new Button();
stopServer.Parent = this;
stopServer.Text = "Stop Server";
stopServer.Location = new Point(260,32);
stopServer.Size = new Size(7 * Font.Height, 2 * Font.Height);
stopServer.Click += new EventHandler(ButtonStopOnClick);
server = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
IPEndPoint iep = new IPEndPoint(IPAddress.Any, 9050);
server.Bind(iep);
server.Listen(5);
server.BeginAccept(new AsyncCallback(AcceptConn), server);
}
void ButtonStopOnClick(object obj, EventArgs ea)
{
Close();
}
void AcceptConn(IAsyncResult iar)
{
Socket oldserver = (Socket)iar.AsyncState;
Socket client = oldserver.EndAccept(iar);
conStatus.Text = "Connected to: " + client.RemoteEndPoint.ToString();
string stringData = "Welcome to my server";
byte[] message1 = Encoding.ASCII.GetBytes(stringData);
client.BeginSend(message1, 0, message1.Length, SocketFlags.None,
new AsyncCallback(SendData), client);
}
void SendData(IAsyncResult iar)
{
Socket client = (Socket)iar.AsyncState;
int sent = client.EndSend(iar);
client.BeginReceive(data, 0, size, SocketFlags.None,
new AsyncCallback(ReceiveData), client);
}
void ReceiveData(IAsyncResult iar)
{
Socket client = (Socket)iar.AsyncState;
int recv = client.EndReceive(iar);
if (recv == 0)
{
client.Close();
conStatus.Text = "Waiting for client...";
server.BeginAccept(new AsyncCallback(AcceptConn), server);
return;
}
string receivedData = Encoding.ASCII.GetString(data, 0, recv);
results.Items.Add(receivedData);
byte[] message2 = Encoding.ASCII.GetBytes(receivedData);
client.BeginSend(message2, 0, message2.Length, SocketFlags.None,
new AsyncCallback(SendData), client);
}
public static void Main()
{
Application.Run(new AsyncTcpSrvr());
}
}
Tcp Listener Sample
/*
C# Network Programming
by Richard Blum
Publisher: Sybex
ISBN: 0782141765
*/
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
public class TcpListenerSample
{
public static void Main()
{
int recv;
byte[] data = new byte[1024];
TcpListener newsock = new TcpListener(9050);
newsock.Start();
Console.WriteLine("Waiting for a client...");
TcpClient client = newsock.AcceptTcpClient();
NetworkStream ns = client.GetStream();
string welcome = "Welcome to my test server";
data = Encoding.ASCII.GetBytes(welcome);
ns.Write(data, 0, data.Length);
while(true)
{
data = new byte[1024];
recv = ns.Read(data, 0, data.Length);
if (recv == 0)
break;
Console.WriteLine(
Encoding.ASCII.GetString(data, 0, recv));
ns.Write(data, 0, recv);
}
ns.Close();
client.Close();
newsock.Stop();
}
}
Network Order Server
/*
C# Network Programming
by Richard Blum
Publisher: Sybex
ISBN: 0782141765
*/
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
public class NetworkOrderSrvr
{
public static void Main()
{
int recv;
byte[] data = new byte[1024];
TcpListener server = new TcpListener(9050);
server.Start();
Console.WriteLine("waiting for a client...");
TcpClient client = server.AcceptTcpClient();
NetworkStream ns = client.GetStream();
string welcome = "Welcome to my test server";
data = Encoding.ASCII.GetBytes(welcome);
ns.Write(data, 0, data.Length);
ns.Flush();
data = new byte[2];
recv = ns.Read(data, 0, data.Length);
short test1t = BitConverter.ToInt16(data, 0);
short test1 = IPAddress.NetworkToHostOrder(test1t);
Console.WriteLine("received test1 = {0}", test1);
data = new byte[4];
recv = ns.Read(data, 0, data.Length);
int test2t = BitConverter.ToInt32(data, 0);
int test2 = IPAddress.NetworkToHostOrder(test2t);
Console.WriteLine("received test2 = {0}", test2);
data = new byte[8];
recv = ns.Read(data, 0, data.Length);
long test3t = BitConverter.ToInt64(data, 0);
long test3 = IPAddress.NetworkToHostOrder(test3t);
Console.WriteLine("received test3 = {0}", test3);
ns.Close();
client.Close();
server.Stop();
}
}
Employee Server
/*
C# Network Programming
by Richard Blum
Publisher: Sybex
ISBN: 0782141765
*/
using System;
using System.Text;
using System.Net;
using System.Net.Sockets;
public class EmployeeSrvr
{
public static void Main()
{
byte[] data = new byte[1024];
TcpListener server = new TcpListener(9050);
server.Start();
TcpClient client = server.AcceptTcpClient();
NetworkStream ns = client.GetStream();
byte[] size = new byte[2];
int recv = ns.Read(size, 0, 2);
int packsize = BitConverter.ToInt16(size, 0);
Console.WriteLine("packet size = {0}", packsize);
recv = ns.Read(data, 0, packsize);
Employee emp1 = new Employee(data);
Console.WriteLine("emp1.EmployeeID = {0}", emp1.EmployeeID);
Console.WriteLine("emp1.LastName = {0}", emp1.LastName);
Console.WriteLine("emp1.FirstName = {0}", emp1.FirstName);
Console.WriteLine("emp1.YearsService = {0}", emp1.YearsService);
Console.WriteLine("emp1.Salary = {0}
", emp1.Salary);
size = new byte[2];
recv = ns.Read(size, 0, 2);
packsize = BitConverter.ToInt16(size, 0);
data = new byte[packsize];
Console.WriteLine("packet size = {0}", packsize);
recv = ns.Read(data, 0, packsize);
Employee emp2 = new Employee(data);
Console.WriteLine("emp2.EmployeeID = {0}", emp2.EmployeeID);
Console.WriteLine("emp2.LastName = {0}", emp2.LastName);
Console.WriteLine("emp2.FirstName = {0}", emp2.FirstName);
Console.WriteLine("emp2.YearsService = {0}", emp2.YearsService);
Console.WriteLine("emp2.Salary = {0}", emp2.Salary);
ns.Close();
client.Close();
server.Stop();
}
}
public class Employee {
public int EmployeeID;
private int LastNameSize;
public string LastName;
private int FirstNameSize;
public string FirstName;
public int YearsService;
public double Salary;
public int size;
public Employee()
{
}
public Employee(byte[] data)
{
int place = 0;
EmployeeID = BitConverter.ToInt32(data, place);
place += 4;
LastNameSize = BitConverter.ToInt32(data, place);
place += 4;
LastName = Encoding.ASCII.GetString(data, place, LastNameSize);
place = place + LastNameSize;
FirstNameSize = BitConverter.ToInt32(data, place);
place += 4;
FirstName = Encoding.ASCII.GetString(data, place, FirstNameSize);
place += FirstNameSize;
YearsService = BitConverter.ToInt32(data, place);
place += 4;
Salary = BitConverter.ToDouble(data, place);
}
public byte[] GetBytes()
{
byte[] data = new byte[1024];
int place = 0;
Buffer.BlockCopy(BitConverter.GetBytes(EmployeeID), 0, data, place, 4);
place += 4;
Buffer.BlockCopy(BitConverter.GetBytes(LastName.Length), 0, data, place, 4);
place += 4;
Buffer.BlockCopy(Encoding.ASCII.GetBytes(LastName), 0, data, place, LastName.Length);
place += LastName.Length;
Buffer.BlockCopy(BitConverter.GetBytes(FirstName.Length), 0, data, place, 4);
place += 4;
Buffer.BlockCopy(Encoding.ASCII.GetBytes(FirstName), 0, data, place, FirstName.Length);
place += FirstName.Length;
Buffer.BlockCopy(BitConverter.GetBytes(YearsService), 0, data, place, 4);
place += 4;
Buffer.BlockCopy(BitConverter.GetBytes(Salary), 0, data, place, 8);
place += 8;
size = place;
return data;
}
}
Var Tcp Server
/*
C# Network Programming
by Richard Blum
Publisher: Sybex
ISBN: 0782141765
*/
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
public class VarTcpSrvr
{
private static int SendVarData(Socket s, byte[] data)
{
int total = 0;
int size = data.Length;
int dataleft = size;
int sent;
byte[] datasize = new byte[4];
datasize = BitConverter.GetBytes(size);
sent = s.Send(datasize);
while (total < size) { sent = s.Send(data, total, dataleft, SocketFlags.None); total += sent; dataleft -= sent; } return total; } private static byte[] ReceiveVarData(Socket s) { int total = 0; int recv; byte[] datasize = new byte[4]; recv = s.Receive(datasize, 0, 4, 0); int size = BitConverter.ToInt32(datasize, 0); int dataleft = size; byte[] data = new byte[size]; while(total < size) { recv = s.Receive(data, total, dataleft, 0); if (recv == 0) { data = Encoding.ASCII.GetBytes("exit "); break; } total += recv; dataleft -= recv; } return data; } public static void Main() { byte[] data = new byte[1024]; IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 9050); Socket newsock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); newsock.Bind(ipep); newsock.Listen(10); Console.WriteLine("Waiting for a client..."); Socket client = newsock.Accept(); IPEndPoint newclient = (IPEndPoint)client.RemoteEndPoint; Console.WriteLine("Connected with {0} at port {1}", newclient.Address, newclient.Port); string welcome = "Welcome to my test server"; data = Encoding.ASCII.GetBytes(welcome); int sent = SendVarData(client, data); for (int i = 0; i < 5; i++) { data = ReceiveVarData(client); Console.WriteLine(Encoding.ASCII.GetString(data)); } Console.WriteLine("Disconnected from {0}", newclient.Address); client.Close(); newsock.Close(); } } [/csharp]
Simple Tcp Server
/*
C# Network Programming
by Richard Blum
Publisher: Sybex
ISBN: 0782141765
*/
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
public class SimpleTcpSrvr
{
public static void Main()
{
int recv;
byte[] data = new byte[1024];
IPEndPoint ipep = new IPEndPoint(IPAddress.Any,
9050);
Socket newsock = new
Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
newsock.Bind(ipep);
newsock.Listen(10);
Console.WriteLine("Waiting for a client...");
Socket client = newsock.Accept();
IPEndPoint clientep =
(IPEndPoint)client.RemoteEndPoint;
Console.WriteLine("Connected with {0} at port {1}",
clientep.Address, clientep.Port);
string welcome = "Welcome to my test server";
data = Encoding.ASCII.GetBytes(welcome);
client.Send(data, data.Length,
SocketFlags.None);
while(true)
{
data = new byte[1024];
recv = client.Receive(data);
if (recv == 0)
break;
Console.WriteLine(
Encoding.ASCII.GetString(data, 0, recv));
client.Send(data, recv, SocketFlags.None);
}
Console.WriteLine("Disconnected from {0}",
clientep.Address);
client.Close();
newsock.Close();
}
}

