Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 14

Fundamental Network

Programming
Socket in C#

Lecturer: MSc. Dang Le Bao Chuong Spring 2022


Agenda

I. Review Socket

II. Socket in C#
I. C# Socket class

II. UdpClient class

III. TcpListener & TcpClient class


Socket programming
goal: learn how to build client/server applications that
communicate using sockets
socket: door between application process and end-end-transport
protocol
application application
socket controlled by
process process app developer

transport transport
network network controlled
link
by OS
link Internet
physical physical
Socket programming
Two socket types for two transport services:
 UDP: unreliable datagram
 TCP: reliable, byte stream-oriented
Application Example:
1. client reads a line of characters (data) from its keyboard and sends
data to server
2. server receives the data and converts characters to uppercase
3. server sends modified data to client
4. client receives modified data and displays line on its screen
Socket programming with UDP
UDP: no “connection” between client
and server:
• no handshaking before sending data
• sender explicitly attaches IP destination
address and port # to each packet
• receiver extracts sender IP address and
port# from received packet

UDP: transmitted data may be lost or received out-of-order


Application viewpoint:
 UDP provides unreliable transfer of groups of bytes (“datagrams”)
between client and server processes
Client/server socket interaction: UDP
server (running on serverIP) client
create socket:
create socket, port= x: clientSocket =
serverSocket = socket(AF_INET,SOCK_DGRAM)
socket(AF_INET,SOCK_DGRAM)
Create datagram with serverIP address
And port=x; send datagram via
read datagram from clientSocket
serverSocket

write reply to
serverSocket read datagram from
specifying clientSocket
client address,
port number close
clientSocket
Example app: UDP client
UDPClient based on C# Socket
create UDP socket for 1. Socket socket
sending to server
= new Socket(AddressFamily.InterNetwork, SocketType.Dgram,
ProtocolType.Udp);
2. IPEndPoint ep = new IPEndPoint(IPAddress.Parse("192.168.2.255"),
11000);
attach server name, port to message; send into socket 3. byte[] send_buffer = Encoding.ASCII.GetBytes(“Text to send”);
4. socket.SendTo(send_buffer, ep);
read reply characters from socket into string 5. Byte[] buffer = new byte[1024];
6. socket.Receive(buffer);
print out received string and close socket 7. String data = Encoding.ASCII.GetString(buffer);
Example app: UDP server
UDPServer based on c#
create UDP socket 1. UdpClient listener = new UdpClient(11000);
2. IPEndPoint groupEP = new IPEndPoint(IPAddress.Any, listenPort);
3. string received_data;
bind socket to local port number 11000 4. byte[] receive_byte_array;
loop forever 5. while (true)
{
Read from UDP socket into message, getting
receive_byte_array = listener.Receive(ref groupEP);
client’s address (client IP and port)
received_data = Encoding.ASCII.GetString(receive_byte_array, 0,
receive_byte_array.Length);
}
6. listener.Close();
Socket programming with TCP
Client must contact server  when contacted by client, server
• server process must first be running TCP creates new socket for server
• server must have created socket
process to communicate with that
(door) that welcomes client’s particular client
contact • allows server to talk with multiple
clients
Client contacts server by: • source port numbers used to
• Creating TCP socket, specifying IP distinguish clients (more in Chap 3)
address, port number of server
process Application viewpoint
• when client creates socket: client TCP provides reliable, in-order
TCP establishes connection to byte-stream transfer (“pipe”)
server TCP between client and server
processes
Client/server socket interaction: TCP
server (running on hostid) client
create socket,
port=x, for incoming
request:
serverSocket = socket()

wait for incoming create socket,


connection request
TCP connect to hostid, port=x
connectionSocket = connection setup clientSocket = socket()
serverSocket.accept()

send request using


read request from clientSocket
connectionSocket

write reply to
connectionSocket read reply from
clientSocket
close
connectionSocket close
clientSocket
Example app: TCP client
TCPClient based on C# Socket

1. IPEndPoint remoteEP = new IPEndPoint(ipAddress,11000);


create TCP socket for server,
2. Socket sender = new Socket(ipAddress.AddressFamily,
remote port 11000
SocketType.Stream, ProtocolType.Tcp );
No need to attach server name, port 3. sender.Connect(remoteEP);
4. sender.RemoteEndPoint.ToString());
5. byte[] msg = Encoding.ASCII.GetBytes("This is a
test<EOF>"); int bytesSent = sender.Send(msg);
6. int bytesRec = sender.Receive(bytes);
sender.Shutdown(SocketShutdown.Both); sender.Close();
Example app: TCP server
TCPServer based on C# Socket
1. byte[] bytes = new Byte[1024];
2. IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000);
create TCP welcoming socket 3. Socket listener = new Socket(ipAddress.AddressFamily,
SocketType.Stream, ProtocolType.Tcp );
server begins listening for 4. listener.Bind(localEndPoint);
incoming TCP requests 5. listener.Listen(10);
loop forever 6. while (true) {
server waits on accept() for incoming 7. Socket handler = listener.Accept();
requests, new socket created on return 8. String data = null;
9. while (true) {
read bytes from socket (but 10. int bytesRec = handler.Receive(bytes);
not address as in UDP) 11. data += Encoding.ASCII.GetString(bytes,0,bytesRec);
12. if (data.IndexOf("<EOF>") > -1) { break; }
13. }
14. byte[] msg = Encoding.ASCII.GetBytes(data);
15. handler.Send(msg);
close connection to this client (but not 16. handler.Shutdown(SocketShutdown.Both);
welcoming socket) 17. handler.Close();
References
1. Socket: https://docs.microsoft.com/vi-vn/dotnet/framework/network-programming/synchronous-client-socket-
example
2. https://www.c-sharpcorner.com/article/a-simple-multi-threaded-tcpudp-server-and-client-v2/
Assignment week #4
• UDP Chat client-server:
• Client side: student should use C# Socket class
• Server side: student should use C# UdpClient class

You might also like