Socket Communication in C#

Slides:



Advertisements
Similar presentations
Introduction to Sockets Jan Why do we need sockets? Provides an abstraction for interprocess communication.
Advertisements

Asynchronous Sockets SWE 344 Internet Protocols & Client Server Programming.
Socket Programming ENTERPRISE JAVA. 2 Content  Sockets  Streams  Threads  Readings.
A CHAT CLIENT-SERVER MODULE IN JAVA BY MAHTAB M HUSSAIN MAYANK MOHAN ISE 582 FALL 2003 PROJECT.
1 Java Networking – Part I CS , Spring 2008/9.
1 L53 Networking (2). 2 OBJECTIVES In this chapter you will learn:  To understand Java networking with URLs, sockets and datagrams.  To implement Java.
CIS – Spring Instructors: Geoffrey Fox, Bryan Carpenter Computational Science and.
Client Server Model The client machine (or the client process) makes the request for some resource or service, and the server machine (the server process)
2: Application Layer1 Socket Programming. 2: Application Layer2 Socket-programming using TCP Socket: a door between application process and end- end-transport.
1 The Warehouse Program. 2 A console program. Listens for connect requests from the call center program. Accepts connection. Reads message. Order ID Prints.
CEG3185 Tutorial 4 Prepared by Zhenxia Zhang Revised by Jiying Zhao (2015w)
TCP Sockets Reliable Communication. TCP As mentioned before, TCP sits on top of other layers (IP, hardware) and implements Reliability In-order delivery.
NAVY Research Group Department of Computer Science Faculty of Electrical Engineering and Computer Science VŠB-TUO 17. listopadu Ostrava-Poruba.
Dr. John P. Abraham Professor University of Texas Pan American Internet Applications and Network Programming.
Assignment 3 A Client/Server Application: Chatroom.
Network Layer Programing Connection-Oriented Sockets SWE 344 Internet Protocols & Client Server Programming.
TCP/IP protocols Communication over Internet is mostly TCP/IP (Transmission Control Protocol over Internet Protocol) TCP/IP "stack" is software which allows.
.NET & C# Introduction 11 March, 2004 Yusung Kim CS441 Introduction to Computer Networking.
NET0183 Networks and Communications Lecture 31 The Socket API 8/25/20091 NET0183 Networks and Communications by Dr Andy Brooks Lecture powerpoints from.
LOGO E-Radio code presentation Prepared By Abdullah Mustafa Abu Nada Hussian Abd-Jaleel Shaalan Nael Wael Skaik Software group.
Lector: Aliyev H.U. Lecture №6 Design of client-server communication software. TCP-based network programming TASHKENT UNIVERSITY OF INFORMATION TECHNOLOGIES.
Windows Programming Using C# Internet Programming.
Cli/Serv.: Chat/121 Client/Server Distributed Systems v Objectives –discuss a client/server based chat system –mention two other ways of chatting.
REVIEW On Friday we explored Client-Server Applications with Sockets. Servers must create a ServerSocket object on a specific Port #. They then can wait.
Internet Applications and Network Programming Dr. Abraham Professor UTPA.
School of Engineering and Computer Science Victoria University of Wellington Copyright: Peter Andreae david streader, VUW Echo Networking COMP
Özgür Zeytinci Network Programming Microsoft.NET.
Dr. John P. Abraham Professor University of Texas Pan American Internet Applications and Network Programming.
Multi-Client/Server GUI Application. Overview As part of the TCP.
Lector: Aliyev H.U. Lecture №4 Telecommunication network software design with.NET. Using sockets for network programming TASHKENT UNIVERSITY OF INFORMATION.
Lecture 9 Network programming. Manipulating URLs URL is an acronym for Uniform Resource Locator and is a reference (an address) to a resource on the Internet.
Li Tak Sing COMPS311F. Case study: consumers and producers A fixed size buffer which can hold at most certain integers. A number of producers which generate.
UDP Client-Server. The Socket Class The Socket class provides a set of methods and properties for network communications. The Socket class allows you.
School of Engineering and Computer Science Victoria University of Wellington Copyright: Peter Andreae, VUW Networking COMP # 22.
Networks Sockets and Streams. TCP/IP in action server ports …65535 lower port numbers ( ) are reserved port echo7 time13 ftp20 telnet23.
Network Programming with C# Exceed Camp #2, CPE, KU Day 3.
Connectionless Sockets SWE 344 Internet Protocols & Client Server Programming.
School of Engineering and Computer Science Victoria University of Wellington Copyright: Peter Andreae david streader, VUW Networking and Concurrency COMP.
CS390- Unix Programming Environment CS 390 Unix Programming Environment Java Socket Programming.
Threads & Networking C# offers facilities for multi threading and network programming an application roughly corresponds to a process, handled by the OS.
1 CSCD 330 Network Programming Spring 2014 Some Material in these slides from J.F Kurose and K.W. Ross All material copyright Lecture 7 Application.
12/5/2015.net 1 system.net Contains any network functionallity you would need in c# Several sub namespaces exists to allow for more fined control –System.Net.Sockets.
Java Server Programming Web Interface for Java Programs.
 Socket class ◦ provides a rich set of methods and properties for network communications. The Socket class allows you to perform both synchronous and.
DOTSNBOXES. Overview Dots and Boxes is played originally with the use of paper, pen and 2 players. The Game board is a matrix of points and vary in size.
Prepared by Dr. Jiying Zhao University of Ottawa Canada.
UNIT-6. Basics of Networking TCP/IP Sockets Simple Client Server program Multiple clients Sending file from Server to Client Parallel search server.
Параллельная работа сокетов в C#. Потоки в C# using System; using System.Threading; public class ThreadExample { public static void ThreadProc() { for.
Networking with JavaN-1 Outline Client-Server Example Steps required on the server side Steps required on the client side.
1 CSCD 330 Network Programming Fall 2013 Some Material in these slides from J.F Kurose and K.W. Ross All material copyright Lecture 8a Application.
MT311 Java Application Development and Programming Languages Li Tak Sing ( 李德成 )
Network Programming: Servers. Agenda l Steps for creating a server Create a ServerSocket object Create a Socket object from ServerSocket Create an input.
Spring/2002 Distributed Software Engineering C:\unocourses\4350\slides\DefiningThreads 1 Java API for distributed computing.
Agenda Socket Programming The OSI reference Model The OSI protocol stack Sockets Ports Java classes for sockets Input stream and.
Java Networking I IS Outline  Quiz #3  Network architecture  Protocols  Sockets  Server Sockets  Multi-threaded Servers.
1 Network Communications A Brief Introduction. 2 Network Communications.
CHARLES UNIVERSITY IN PRAGUE faculty of mathematics and physics Advanced.NET Programming I 14 th Lecture Pavel Ježek
School of Engineering and Computer Science Victoria University of Wellington Copyright: Peter Andreae david streader, VUW Echo Networking COMP
Echo Networking COMP
Threads in Java Two ways to start a thread
Lecture 21 Sockets 1 (Not in D&D) Date.
Client-server Programming
網路程式設計 - C# 版 日期 : 2018/12/4.
Internet Applications and Network Programming
.Net Sockets.
Visual Programming COMP-315
Jim Fawcett CSE681 – Software Modeling & Analysis Fall 2008
Advanced .NET Programming I 15th Lecture
Jim Fawcett CSE681 – Software Modeling & Analysis Fall 2008
Jim Fawcett CSE681 – Software Modeling & Analysis Fall 2008
Presentation transcript:

Socket Communication in C#

How Sockets make communication? Socket is a basic object that can do net communication. All net communications are build on Socket operation. In server side, object TcpLinstener is running at an HTTP port and standing by to listen for the calls from Internet. (TcpLinstener is called ServerSocket in Java) In a client side, client Socket call TcpLinstener by web server IP and port OnceTcpLinstener got call, it will execute function accept() and create a socket object in server side to take care communication All socket net communication is use data stream. Object TcpLinstener can go back and listen again.

Server side Client side Socket Socket accept() Initial call TcpListener HTTP Port

Socket Constructor Usual code is: Its main methods are Socket ( AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType ) Usual code is: Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp ); Its main methods are Connect (IPEndPoint) Send(byte[ ]) Receive(byte[ ]) Close()

Connect to a server by IP & Port# In order to make a connection we make an IPEndPoint object of the remote server first. The process is the following: IPHostEntry IpEntry = Dns.GetHostByAddress("129.7.127.103"); IPAddress hostAddress = IpEntry.AddressList[0]; IPEndPoint hostEndPoint = new IPEndPoint(hostAddress, 8001); socket.Connect(hostEndPoint); Remarks: 1. Dns is a class that deals with the domain names issues. 2. If use the remote server name, then we have to use code like IPHostEntry IpEntry = Dns.GetHostByName("www.nba.com"); 3. One PC could have multiple IPs, but the above code will get an IPAddress object for string "129.7.127.103". 4. Number 8001 is the port number of the remote server.

Send Data All data in net communication must be of type byte array. Therefore we must use class ASCIIEncoding object to convert string to bytes and vise versa. ASCIIEncoding asciiEnc = new ASCIIEncoding(); String str = Console.ReadLine(); byte[] binData = asciiEnc.GetBytes(str); socket.Send(binData); Also we can use the following code to control the length of out data socket.Send(binData, 0, binData.Length, SocketFlags.None);

Receive Data Receiving data from net is similar to sending data. After receiving the binary data, use ASCIIEncoding object to convert it to string. ASCIIEncoding asciiEnc = new ASCIIEncoding(); byte[] binData = new byte[255]; int k = socket.Receive(binData); String str = asciiEnc.GetString(binData,0, k); Integer k is the total bytes received. If the input data is longer then the length of binData, some data could be lost. To prevent that case, we use the following code to control the length of input data no more than 255. socket. Receive(binData, 0, binData.Length, SocketFlags.None); If k==0, the connection to the server is lost.

Use TcpClient object Like Socket, class TcpClient object can do TCP NetWork communication too. The connection code is very simple: TcpClient tcpClient = new TcpClient(); tcpClient.Connect("129.7.127.103",8001); However, it must use a Stream object to read and write. ASCIIEncoding asciiEnc = new ASCIIEncoding(); String str = Console.ReadLine(); byte[] binData = asciiEnc.GetBytes(str); Stream stream = tcpClient.GetStream(); stream.Write(binData, 0, binData.Length); // send data out Receiving code is byte[] binDataIn = new byte[255]; int k=stream.Read(binDataIn, 0, 255); //receive data

Server side TcpListener object In server side , we use class TcpListener object to build the connection to the client socket or TcpCliet object. IPAddress ipAddr = IPAddress.Parse("129.7.127.103"); TcpListener netListener = new TcpListener(ipAddr, 8001); netListener.Start(); // start to listen "129.7.127.103" is the IP number of the server. If the server only has one IP number, then we can get it by code: String ipNum = Dns.GetHostByName().AddressList[0].ToString(). Once client side calls, it will trig the following function and generate a socket object to do communication. Socket socket = netListener.AcceptSocket(); If no calls sent from client sides, this function will be standing by and waiting for the call from client side

Client Socket example using System; using System.IO; using System.Net; using System.Text; using System.Net.Sockets; public class client { public static void Main() Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp ); try { IPHostEntry IpEntry = Dns.GetHostByAddress("192.168.1.103"); IPAddress hostAddress = IpEntry.AddressList[0]; IPEndPoint hostEndPoint = new IPEndPoint(hostAddress, 8001); Console.WriteLine("Connecting....."); socket.Connect(hostEndPoint);

if(socket.Connected) Console.WriteLine("Connected"); Console.Write("Enter the string to be transmitted : "); ASCIIEncoding asciiEnc= new ASCIIEncoding(); while(true) { string str=Console.ReadLine(); if(str.ToLower() =="quit") break; byte[] binDataOut = asciiEnc.GetBytes(str); socket.Send(binDataOut, 0, binDataOut.Length,SocketFlags.None); byte[] binDataIn=new byte[255]; int k = socket.Receive(binDataIn, 0, 255 , SocketFlags.None); string msg = asciiEnc.GetString(binDataIn, 0, k); Console.Write(msg); } socket.Close(); catch (Exception e) Console.WriteLine("Error..... " + e.StackTrace); Console.ReadLine(); } }

Client TcpClient example using System; using System.IO; using System.Net; using System.Text; using System.Net.Sockets; public class client { public static void Main() TcpClient tcp = new TcpClient(); try Console.WriteLine("Connecting....."); tcp.Connect("192.168.1.103", 8001); Console.WriteLine("Connected"); Console.WriteLine("Enter the string to be transmitted : "); ASCIIEncoding asciiEnc= new ASCIIEncoding(); Stream stream = tcp.GetStream();

while(true) { string str=Console.ReadLine(); if(str.ToLower() =="quit") break; byte[] binDataOut = asciiEnc.GetBytes(str); stream. Write(binDataOut, 0, binDataOut.Length); byte[] binDataIn=new byte[255]; int k = stream.Read(binDataIn,0,255); string msg = asciiEnc.GetString(binDataIn, 0, k); Console.Write(msg); } Tcp.Close(); Console.ReadLine(); } // end of try catch (Exception e) Console.WriteLine("Error..... " + e.StackTrace);

Server Socket example using System; using System.Net; using System.Text; using System.Net.Sockets; public class server { public static void Main() bool connected =false; try{ IPAddress ipAddr = IPAddress.Parse("192.168.1.103"); TcpListener myListener = new TcpListener(ipAddr,8001); myListener.Start(); Console.WriteLine("The server is running at port: " + myListener.LocalEndpoint); Console.WriteLine("Waiting for a connection....."); Socket socket = myListener.AcceptSocket(); Console.WriteLine("Connection accepted from" + socket.RemoteEndPoint)

connected =true; byte[] binDataIn = new byte[255]; Console.WriteLine("The message from client side... "); while(true) { int k=socket.Receive(binDataIn); if(k==0) break; ASCIIEncoding asciiEnc = new ASCIIEncoding(); string msg = asciiEnc.GetString(binDataIn, 0, k); byte [] binOut = new byte [k]; for(int i=0; i<k; i++)binOut[i] = binDataIn[k-i-1]; socket.Send(binOut); Console.WriteLine(msg); } socket.Close(); myListener.Stop(); catch (Exception e) { if(!connected)Console.WriteLine("Error..... " + e.ToString() ); } Console.WriteLine("\nClient closed connection"); Console.ReadLine(); } }

Output

Multiple Threading From last example, we can see that TcpListener build connection while sockets do communication Therefore one TcpListener can serve for many client sockets. To this purpose we must use multiple thread. Thread is a connection between program and operating system. With a thread, system can arrange CPU time to execute the program instructions. Any program has a natural thread that from Main() function. Some program operation will control thread until it finished. Such as play a music. If the program only has one thread, during the music playing time, the window cannot be moved or resized. TcpListener needs thread for standing by and listening. Socket needs thread to do communication. Therefore we need multiple threads for socket communications

Add Thread object First we must add using system.Threading; Create a function in the class, which must be void and no argument, suppose it is: private void foo() {…} Then create a Thread object in the following way: Thread t = new Thread(new ThreadStart(foo)); t.Start(); 4. Then function foo() will get a new Thread 5. We can call t.Suspend() and t.Resume(). 6. To destroy a thread, call t.Abort()

Communication class public class Communication { Socket socket=null; int n; public Communication(Socket sock, int k) { socket = sock; n = k; } public void Talk() byte[] binDataIn = new byte [255]; Console.WriteLine("The socket " + n + " begin to work... "); try while(true) int k=socket.Receive(binDataIn); If (k==0) break; // if client closed

ASCIIEncoding asciiEnc = new ASCIIEncoding(); string msg = asciiEnc.GetString(binDataIn,0,k); byte [] binOut = new byte [k]; for(int i=0; i<k; i++) { binOut[i] = binDataIn[k-i-1]; } socket.Send(binOut); Console.WriteLine("from client " + n +" " +msg); catch(Exception) { } // if client shut down Console.WriteLine("Client " + n +" Disconnected"); socket.Close();

How to Assign Thread ? int count = 0; while(true) { Socket socket = myListener.AcceptSocket(); count++; Console.WriteLine("Connection " + count + " accepted from "+socket.RemoteEndPoint); Communication com = new Communication(socket, count); Thread t = new Thread(new ThreadStart(com.Talk)); t.Start(); } // this is listening loop After call t.Start(), the thread will assign to function Talk() of class Communication object com.

Communication between Clients In this case, we must put all server side sockets object in a container, so that we can send message to every client by using this container. Socket 1 Client socket 1 Socket 2 Client socket 2 ArrayList Server side

Use ArrayList to store object We must store all socket in ArrayList object that can be accessed by all threads. The basic methods of ArrayList object are: Add(object obj); Remove(object obj); ArrayList list = new ArrayList(); Communication com1 = new Communication(socket, count); List.Add(com1); Its property Count is the total objects in the list. To access its object use index function []. However, we must do casting operation to get original class object. Communication com2 =( Communication) list[3];

Synchronized operation When some data is shared by multiple threads, we must do Synchronized operation. For example if the shared data is written in one thread, we must block all writing process from other threads. Sometimes, we even need to block reading process. In C#, we can use class ReaderWriterLock object to do so. ReaderWriterLock rw = new ReaderWriterLock() static public void remove(object obj) { rw.AcquireWriterLock(Timeout.Infinite); list.Remove(obj) ; rw.ReleaseWriterLock(); }

Server Broadcast example using System; using System.Net; using System.Text; using System.Net.Sockets; using System.Collections; // for ArrayList using System.Threading; public class server { static ArrayList list = new ArrayList(); static ReaderWriterLock rw = new ReaderWriterLock(); static public void remove(object obj) rw.AcquireWriterLock(Timeout.Infinite); list.Remove(obj) ; rw.ReleaseWriterLock(); }

Server Broadcast example static public void AddList(object obj) { rw.AcquireWriterLock(Timeout.Infinite); list.Add(obj) ; rw.ReleaseWriterLock(); } static public void SendToAll(byte[] binData) for(int k = 0; k<list.Count; k++) Communication com = (Communication)list[k]; Socket sock = com.socket; sock.Send(binData);

public static void Main() { bool connected =false; int count =0; TcpListener myListener = null; try { string hostName = Dns.GetHostName(); IPHostEntry ipEntry = Dns.GetHostByName(hostName); myListener = new TcpListener(ipEntry.AddressList[0],8001); myListener.Start(); Console.WriteLine("The server is running at port: " + myListener.LocalEndpoint); Console.WriteLine("Waiting for a connection....."); while(true) { Socket socket=myListener.AcceptSocket(); count++; Console.WriteLine("Connection " + count + " accepted from "+socket.RemoteEndPoint); Communication com = new Communication(socket, count); AddList(com); }

catch (Exception e) { if(!connected)Console.WriteLine("Error..... " + e.ToString() ); } myListener.Stop(); Console.WriteLine("\nClient closed connection"); Console.ReadLine(); public class Communication public Socket socket=null; int n; public Communication(Socket sock, int k) socket = sock; n = k; Thread t = new Thread (new ThreadStart (Talk)); t.Start();

public void Talk() { byte[] binDataIn = new byte [255]; Console.WriteLine("The socket " + n + " begin to work... "); try { while(true) { int k=socket.Receive(binDataIn); if(k==0) break; // if client closed ASCIIEncoding asciiEnc = new ASCIIEncoding(); string msg = asciiEnc.GetString(binDataIn,0,k); msg = "from client " + n +": " + msg; byte[] binDataOut = asciiEnc.GetBytes(msg); SendToAll(binDataOut); Console.WriteLine(msg); } catch(Exception) { } Console.WriteLine("Client " + n +" Disconnected"); remove(this); socket.Close(); }}

Client side In client side we need to add one thread to take care the messages from broadcasting. using System; using System.IO; using System.Net; using System.Text; using System.Net.Sockets; using System.Threading ; public class client { static bool connected = false; static Socket socket = null;

public static void Main() { Console.WriteLine("Please enter the Server IP address"); string IP = Console.ReadLine(); Console.WriteLine("Please enter the Server HTTP port number"); string port = Console.ReadLine(); int p; try{ p = Int32.Parse(port); } catch(Exception) Console.WriteLine("Wrong port number"); return; socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp ); IPHostEntry IpEntry = Dns.GetHostByAddress(IP); IPAddress hostAddress = IpEntry.AddressList[0]; IPEndPoint hostEndPoint = new IPEndPoint(hostAddress, p); Console.WriteLine("Connecting.....");

try { socket.Connect(hostEndPoint); } catch(Exception) { Console.WriteLine("No connection to server\nPress enter to exit"); Console.ReadLine(); return; connected = socket.Connected; if(connected) Console.WriteLine("Connected"); Console.WriteLine("Enter the string to be transmitted : "); ASCIIEncoding asciiEnc= new ASCIIEncoding(); Thread t = new Thread(new ThreadStart(GetMsg)); t.Start(); while(connected){ String str=Console.ReadLine(); if(str.ToLower() =="quit") break; byte[] binData = asciiEnc.GetBytes(str); socket.Send(binData, 0, binData.Length, SocketFlags.None); socket.Close();

catch (Exception e) { Console.WriteLine("Error..... " + e.StackTrace); Console.ReadLine(); } connected = false; static private void GetMsg() ASCIIEncoding asciiEnc= new ASCIIEncoding(); while(connected) byte[] bb=new byte[255]; int k = socket.Receive(bb, 0, bb.Length , SocketFlags.None); string msg = asciiEnc.GetString(bb,0,k); Console.WriteLine( msg);