SlideShare a Scribd company logo
Chapter 3 Socket Programming Lecturer: Sivadon Chaisiri Mathematics, Statistics and Computer Department Faculty of Science, Ubon Rajathanee University
Layered Protocols
Metadata in a Messages
Protocols Application = HTTP, FTP, SMTP, NSF, Telnet, SSH, ECHO, …  Presentation = SMB, NCP, … Session = SSH, NetBIOS, RPC, … Transport = TCP, UDP, … Network = IP, ICMP, IPX Data link = Ethernet, Token Ring, ISDN, … Physical = 100BASE-T, 1000BASE-T, 802.11
TCP/IP four-layer model
IP, TCP, and UDP IP (Internet Protocol) TCP (Transmission Control Protocol) UDP (User Datagram Protocol)   = Unreliable communication, no ordering guarantee   (e.g., DNS, TFTP, VoIP, …)
Ports A port is a special number  present in the data packet.  Ports are typically used to map data to a particular process running on a computer (i.e., which process associates with the data determining by port number) IANA is responsible for assigning TCP and UDP port numbers to specific used. Well-known ports   (0-1023) Registered ports (1024-49151) Dynamic and/or Private ports (49152-65535)
Ports and Applications
The Client-Server Model
Socket Application A socket is a connection between two hosts (endpoints). A socket can perform 7 basic operations. Connect to a remote machine Send data Receive data Close a connection Bind to a port Listen for incoming data Accept connections from remote machines on the bound port
Endpoint-to-Endpoint Communications
Java and Socket java.net.Socket Constructors:  Socket(InetAddress address, int port) Socket(String host, int port) Socket(InetAddress address, int port,  InetAddress localAddr, int localPort) Methods:  InputStream getInputStream() Out putStream getOutputStream() void close() InetAddress getLocalAddress() int getLocalPort() void setSoTimeout(int timeout)
Java and Socket java.net.ServerSocket Constructors:  ServerSocket(int port) Methods:  Socket accept() void close() void setSoTimeout(int timeout)
Socket and ServerSocket
Streams More stream classes InputStream : DataInputStream, ObjectInputStream OutputStream : DataOutputStream, ObjectOutputStream
Filters of Streams
Code: Socket Information import java . net . Socket; public class  SocketInfo  { public static void main ( String []  args )  throws Exception { Socket socket  =  new Socket (" www . sanook . com " , 80 ) ; System . out . println (" Connected to  " +    socket . getInetAddress () + "  on port  " +  socket . getPort () + "  from port  " +  socket . getLocalPort () + "  of  " +  socket . getLocalAddress ()) ; } }
Steps to develop a socket app Client-Side Bind  Socket  object with a specified host&port then connect to the host&port [option] Send data via stream (from getOutputStream) Wait for a response of the host via getInputStream Server-Side Bind  ServerSocket  object with a specified port Listening for the incoming requesting Accept connection while listened to an incoming contact and get its Socket reference Send/Receive data via streams of the Socket Object
Code: Time Server import java . io . DataOutputStream; import java . net . *; import java . util . Date; public class  TimeServer  { public static void main ( String []  args )  throws Exception { ServerSocket server  =  new ServerSocket ( 7000 ) ; System . out . println (" Server is started ") ; while ( true )  { Socket socket  =  server . accept () ; DataOutputStream dos  =  new      DataOutputStream ( socket . getOutputStream ()) ; String time  =  new Date (). toString () ; dos . writeUTF ( time ) ; socket . close () ; } } }
Code: Time Client import java . io . DataInputStream; import java . io . DataOutputStream; import java . net . Socket; public class  TimeClient  { public static void main ( String []  args )  throws Exception { Socket socket  =  new Socket (" localhost " , 7000 ) ; DataInputStream din = new  DataInputStream ( socket . getInputStream ()) ; String time  =  din . readUTF () ; System . out . println ( time ) ; } }
Code: Hello Server import java . io . *; import java . net . *; public class  HelloServer  { public static void main ( String []  args )  throws Exception { ServerSocket server  =  new ServerSocket ( 12345 ) ; System . out . println (" Server is started ") ; while ( true )  { Socket socket  =  server . accept () ; DataInputStream dis  =  new  DataInputStream ( socket . getInputStream ()) ; DataOutputStream dos  =  new  DataOutputStream ( socket . getOutputStream ()) ; String name  =  dis . readUTF () ; System . out . println (" I see  " +  name ) ; dos . writeUTF (" Hello  " +  name ) ; socket . close () ; } } }
Code: Hello Client import java . io*; import java . net . *; public class  HelloClient  { public static void main ( String []  args )  throws Exception { Socket socket  =  new Socket (" localhost " , 12345 ) ; DataInputStream din  =  new  DataInputStream ( socket . getInputStream ()) ; DataOutputStream dos  =  new  DataOutputStream ( socket . getOutputStream ()) ; String name  = " World " ; if  ( args . length > 0 )  name  =  args [ 0 ] ; dos . writeUTF ( name ) ; String message  =  din . readUTF () ; System . out . println ( message ) ; } }
Code: Busy Hello Server import java . io . *; import java . net . *; public class  BusyHelloServer  { public static void main ( String []  args )  throws Exception { ServerSocket server  =  new ServerSocket ( 12345 ) ; while ( true )  { Socket socket  =  server . accept () ; DataInputStream dis  =  new  DataInputStream ( socket . getInputStream ()) ; DataOutputStream dos  =  new  DataOutputStream ( socket . getOutputStream ()) ; String name  =  dis . readUTF () ; System . out . println (&quot; I see  &quot; +  name ) ; for  ( int i  =  0 ; i < 10 ; i ++)  {   Thread . sleep ( 1000 ) ;   System . out . println (&quot; Delay for  &quot; +  name  + &quot;  # &quot; +  i ) ; } dos . writeUTF (&quot; Hello  &quot; +  name ) ; socket . close () ; } } }
Code:  Multithread Hello Server import java . io . *; import java . net . *; public class  ThreadingHelloServer   extends Thread  { Socket soc; public ThreadingHelloServer ( Socket soc )  { this . soc  =  soc; } public void run ()  {   try { DataInputStream dis  =  new      DataInputStream ( soc . getInputStream ()) ; DataOutputStream dos  =  new DataOutputStream ( soc . getOutputStream ()) ; String name  =  dis . readUTF () ; System . out . println (&quot; I see  &quot; +  name ) ; for  ( int i  =  0 ; i < 10 ; i ++)  {   Thread . sleep ( 1000 ) ;   System . out . println (&quot; Delay for  &quot; +  name  + &quot;  # &quot; +  i ) ; } dos . writeUTF (&quot; Hello  &quot; +  name ) ; soc . close () ;   } catch ( Exception ex )  {ex . printStackTrace () ;} } public static void main ( String []  args )  throws Exception { ServerSocket server  =  new ServerSocket ( 12345 ) ; while ( true )  { Socket socket  =  server . accept () ;   new ThreadingHelloServer ( socket )  .start () ; } } }
Code:  Multithread Hello Server   (Short Form) import java.io.*; import java.net.*; public class  ThreadingHelloServer2  { public static void main(String[] args) throws Exception {   ServerSocket server = new ServerSocket(12345);   System.out.println(&quot;Server is started&quot;);   while(true) {   final Socket socket = server.accept();   Thread t = new Thread() {   public void run() {   try { DataInputStream dis = new   DataInputStream(socket.getInputStream()); DataOutputStream dos = new   DataOutputStream(socket.getOutputStream()); String name = dis.readUTF(); System.out.println(&quot;I see &quot; + name); for (int i = 0 ; i < 10 ; i++) {   Thread.sleep(1000);   System.out.println(&quot;Delay for &quot; + name + &quot; #&quot; + i); } dos.writeUTF(&quot;Hello &quot; + name); socket.close();   } catch(Exception ex) { ex.printStackTrace(); } }}; t.start(); }}}
The End Any Questions?

More Related Content

PDF
ikh331-06-distributed-programming
PPT
Pemrograman Jaringan
PPT
Networking Core Concept
PPT
Socket System Calls
PDF
Advanced Sockets Programming
KEY
Non blocking io with netty
PPT
Ppt of socket
PDF
The Ring programming language version 1.6 book - Part 28 of 189
ikh331-06-distributed-programming
Pemrograman Jaringan
Networking Core Concept
Socket System Calls
Advanced Sockets Programming
Non blocking io with netty
Ppt of socket
The Ring programming language version 1.6 book - Part 28 of 189

What's hot (20)

PDF
Lecture10
PDF
File Transfer Through Sockets
PDF
Network Sockets
PDF
Lecture6
DOCX
Winform
PDF
Java- Datagram Socket class & Datagram Packet class
PPT
Sockets intro
DOCX
JavaExamples
PDF
PPTX
PDF
Relayd: a load balancer for OpenBSD
PPTX
Socket.io v.0.8.3
PDF
Grails/Groovyによる開発事例紹介
PPTX
Socket programming
PPT
About Those Python Async Concurrent Frameworks - Fantix @ OSTC 2014
PDF
LibreSSL, one year later
PPTX
QA Fest 2019. Saar Rachamim. Developing Tools, While Testing
PPT
Application Layer and Socket Programming
KEY
The Ruby Guide to *nix Plumbing: on the quest for efficiency with Ruby [M|K]RI
PPT
Socket programming-tutorial-sk
Lecture10
File Transfer Through Sockets
Network Sockets
Lecture6
Winform
Java- Datagram Socket class & Datagram Packet class
Sockets intro
JavaExamples
Relayd: a load balancer for OpenBSD
Socket.io v.0.8.3
Grails/Groovyによる開発事例紹介
Socket programming
About Those Python Async Concurrent Frameworks - Fantix @ OSTC 2014
LibreSSL, one year later
QA Fest 2019. Saar Rachamim. Developing Tools, While Testing
Application Layer and Socket Programming
The Ruby Guide to *nix Plumbing: on the quest for efficiency with Ruby [M|K]RI
Socket programming-tutorial-sk
Ad

Viewers also liked (19)

PDF
Intelbloggerday08
PPT
Present Paper: Protecting Free Expression Online on Freenet
PPT
Remote Call
PDF
Cost Minimization for Provisioning Virtual Servers in Amazon EC2
PDF
02 Ms Online Identity Session 1
PDF
UX勉強会(第十章)
PPT
Research Issues on Resource Discovery & Matching Making
PPT
Research Issues on Grid Resource Brokers
PPT
Optimal Virtual Machine Placement across Multiple Cloud Providers
PDF
Robust Cloud Resource Provisioning for Cloud Computing Environments
PDF
Presentation: Optimal Power Management for Server Farm to Support Green Compu...
PDF
01 All Up Technical Overview
PDF
Optimization of Resource Provisioning Cost in Cloud Computing
PPT
Economic Analysis of Resource Market in Cloud Computing Environment
PPT
Benson Pecha Kucha
PDF
UX勉強会(第十五章)
PDF
動画のあれこれ
PDF
UX勉強会(第五章)
PDF
UX勉強会(第四章)
Intelbloggerday08
Present Paper: Protecting Free Expression Online on Freenet
Remote Call
Cost Minimization for Provisioning Virtual Servers in Amazon EC2
02 Ms Online Identity Session 1
UX勉強会(第十章)
Research Issues on Resource Discovery & Matching Making
Research Issues on Grid Resource Brokers
Optimal Virtual Machine Placement across Multiple Cloud Providers
Robust Cloud Resource Provisioning for Cloud Computing Environments
Presentation: Optimal Power Management for Server Farm to Support Green Compu...
01 All Up Technical Overview
Optimization of Resource Provisioning Cost in Cloud Computing
Economic Analysis of Resource Market in Cloud Computing Environment
Benson Pecha Kucha
UX勉強会(第十五章)
動画のあれこれ
UX勉強会(第五章)
UX勉強会(第四章)
Ad

Similar to Socket Programming (20)

PPT
Sockets
PDF
PPT
Socket programming
PPT
Chapter 4 slides
DOCX
Fia fabila
PDF
201913001 khairunnisa progres_harian
PDF
Tugas 2
PPTX
分散式系統
PPT
Sockets.ppt socket sofcv ohghjagshsdjjhjfb
PPT
Network
DOCX
network programing lab file ,
PPT
Networking & Socket Programming In Java
PPT
Network programming in Java
PPT
TCP IP
PDF
How a network connection is created A network connection is initi.pdf
PDF
java sockets
PPT
Unit 8 Java
DOCX
Please look at the attach See.doc. I am getting this error all th.docx
PPT
Socket Programming in Java.ppt yeh haii
Sockets
Socket programming
Chapter 4 slides
Fia fabila
201913001 khairunnisa progres_harian
Tugas 2
分散式系統
Sockets.ppt socket sofcv ohghjagshsdjjhjfb
Network
network programing lab file ,
Networking & Socket Programming In Java
Network programming in Java
TCP IP
How a network connection is created A network connection is initi.pdf
java sockets
Unit 8 Java
Please look at the attach See.doc. I am getting this error all th.docx
Socket Programming in Java.ppt yeh haii

Recently uploaded (20)

PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PDF
Machine learning based COVID-19 study performance prediction
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PDF
Empathic Computing: Creating Shared Understanding
PDF
CIFDAQ's Market Insight: SEC Turns Pro Crypto
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PPTX
MYSQL Presentation for SQL database connectivity
PPTX
Understanding_Digital_Forensics_Presentation.pptx
PDF
Network Security Unit 5.pdf for BCA BBA.
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PDF
Electronic commerce courselecture one. Pdf
PDF
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
PDF
Encapsulation_ Review paper, used for researhc scholars
PDF
Approach and Philosophy of On baking technology
Advanced methodologies resolving dimensionality complications for autism neur...
Machine learning based COVID-19 study performance prediction
Dropbox Q2 2025 Financial Results & Investor Presentation
Empathic Computing: Creating Shared Understanding
CIFDAQ's Market Insight: SEC Turns Pro Crypto
The Rise and Fall of 3GPP – Time for a Sabbatical?
Building Integrated photovoltaic BIPV_UPV.pdf
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
MYSQL Presentation for SQL database connectivity
Understanding_Digital_Forensics_Presentation.pptx
Network Security Unit 5.pdf for BCA BBA.
Digital-Transformation-Roadmap-for-Companies.pptx
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
Reach Out and Touch Someone: Haptics and Empathic Computing
Chapter 3 Spatial Domain Image Processing.pdf
Electronic commerce courselecture one. Pdf
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
Encapsulation_ Review paper, used for researhc scholars
Approach and Philosophy of On baking technology

Socket Programming

  • 1. Chapter 3 Socket Programming Lecturer: Sivadon Chaisiri Mathematics, Statistics and Computer Department Faculty of Science, Ubon Rajathanee University
  • 3. Metadata in a Messages
  • 4. Protocols Application = HTTP, FTP, SMTP, NSF, Telnet, SSH, ECHO, … Presentation = SMB, NCP, … Session = SSH, NetBIOS, RPC, … Transport = TCP, UDP, … Network = IP, ICMP, IPX Data link = Ethernet, Token Ring, ISDN, … Physical = 100BASE-T, 1000BASE-T, 802.11
  • 6. IP, TCP, and UDP IP (Internet Protocol) TCP (Transmission Control Protocol) UDP (User Datagram Protocol) = Unreliable communication, no ordering guarantee (e.g., DNS, TFTP, VoIP, …)
  • 7. Ports A port is a special number present in the data packet. Ports are typically used to map data to a particular process running on a computer (i.e., which process associates with the data determining by port number) IANA is responsible for assigning TCP and UDP port numbers to specific used. Well-known ports (0-1023) Registered ports (1024-49151) Dynamic and/or Private ports (49152-65535)
  • 10. Socket Application A socket is a connection between two hosts (endpoints). A socket can perform 7 basic operations. Connect to a remote machine Send data Receive data Close a connection Bind to a port Listen for incoming data Accept connections from remote machines on the bound port
  • 12. Java and Socket java.net.Socket Constructors: Socket(InetAddress address, int port) Socket(String host, int port) Socket(InetAddress address, int port, InetAddress localAddr, int localPort) Methods: InputStream getInputStream() Out putStream getOutputStream() void close() InetAddress getLocalAddress() int getLocalPort() void setSoTimeout(int timeout)
  • 13. Java and Socket java.net.ServerSocket Constructors: ServerSocket(int port) Methods: Socket accept() void close() void setSoTimeout(int timeout)
  • 15. Streams More stream classes InputStream : DataInputStream, ObjectInputStream OutputStream : DataOutputStream, ObjectOutputStream
  • 17. Code: Socket Information import java . net . Socket; public class SocketInfo { public static void main ( String [] args ) throws Exception { Socket socket = new Socket (&quot; www . sanook . com &quot; , 80 ) ; System . out . println (&quot; Connected to &quot; + socket . getInetAddress () + &quot; on port &quot; + socket . getPort () + &quot; from port &quot; + socket . getLocalPort () + &quot; of &quot; + socket . getLocalAddress ()) ; } }
  • 18. Steps to develop a socket app Client-Side Bind Socket object with a specified host&port then connect to the host&port [option] Send data via stream (from getOutputStream) Wait for a response of the host via getInputStream Server-Side Bind ServerSocket object with a specified port Listening for the incoming requesting Accept connection while listened to an incoming contact and get its Socket reference Send/Receive data via streams of the Socket Object
  • 19. Code: Time Server import java . io . DataOutputStream; import java . net . *; import java . util . Date; public class TimeServer { public static void main ( String [] args ) throws Exception { ServerSocket server = new ServerSocket ( 7000 ) ; System . out . println (&quot; Server is started &quot;) ; while ( true ) { Socket socket = server . accept () ; DataOutputStream dos = new DataOutputStream ( socket . getOutputStream ()) ; String time = new Date (). toString () ; dos . writeUTF ( time ) ; socket . close () ; } } }
  • 20. Code: Time Client import java . io . DataInputStream; import java . io . DataOutputStream; import java . net . Socket; public class TimeClient { public static void main ( String [] args ) throws Exception { Socket socket = new Socket (&quot; localhost &quot; , 7000 ) ; DataInputStream din = new DataInputStream ( socket . getInputStream ()) ; String time = din . readUTF () ; System . out . println ( time ) ; } }
  • 21. Code: Hello Server import java . io . *; import java . net . *; public class HelloServer { public static void main ( String [] args ) throws Exception { ServerSocket server = new ServerSocket ( 12345 ) ; System . out . println (&quot; Server is started &quot;) ; while ( true ) { Socket socket = server . accept () ; DataInputStream dis = new DataInputStream ( socket . getInputStream ()) ; DataOutputStream dos = new DataOutputStream ( socket . getOutputStream ()) ; String name = dis . readUTF () ; System . out . println (&quot; I see &quot; + name ) ; dos . writeUTF (&quot; Hello &quot; + name ) ; socket . close () ; } } }
  • 22. Code: Hello Client import java . io*; import java . net . *; public class HelloClient { public static void main ( String [] args ) throws Exception { Socket socket = new Socket (&quot; localhost &quot; , 12345 ) ; DataInputStream din = new DataInputStream ( socket . getInputStream ()) ; DataOutputStream dos = new DataOutputStream ( socket . getOutputStream ()) ; String name = &quot; World &quot; ; if ( args . length > 0 ) name = args [ 0 ] ; dos . writeUTF ( name ) ; String message = din . readUTF () ; System . out . println ( message ) ; } }
  • 23. Code: Busy Hello Server import java . io . *; import java . net . *; public class BusyHelloServer { public static void main ( String [] args ) throws Exception { ServerSocket server = new ServerSocket ( 12345 ) ; while ( true ) { Socket socket = server . accept () ; DataInputStream dis = new DataInputStream ( socket . getInputStream ()) ; DataOutputStream dos = new DataOutputStream ( socket . getOutputStream ()) ; String name = dis . readUTF () ; System . out . println (&quot; I see &quot; + name ) ; for ( int i = 0 ; i < 10 ; i ++) { Thread . sleep ( 1000 ) ; System . out . println (&quot; Delay for &quot; + name + &quot; # &quot; + i ) ; } dos . writeUTF (&quot; Hello &quot; + name ) ; socket . close () ; } } }
  • 24. Code: Multithread Hello Server import java . io . *; import java . net . *; public class ThreadingHelloServer extends Thread { Socket soc; public ThreadingHelloServer ( Socket soc ) { this . soc = soc; } public void run () { try { DataInputStream dis = new DataInputStream ( soc . getInputStream ()) ; DataOutputStream dos = new DataOutputStream ( soc . getOutputStream ()) ; String name = dis . readUTF () ; System . out . println (&quot; I see &quot; + name ) ; for ( int i = 0 ; i < 10 ; i ++) { Thread . sleep ( 1000 ) ; System . out . println (&quot; Delay for &quot; + name + &quot; # &quot; + i ) ; } dos . writeUTF (&quot; Hello &quot; + name ) ; soc . close () ; } catch ( Exception ex ) {ex . printStackTrace () ;} } public static void main ( String [] args ) throws Exception { ServerSocket server = new ServerSocket ( 12345 ) ; while ( true ) { Socket socket = server . accept () ; new ThreadingHelloServer ( socket ) .start () ; } } }
  • 25. Code: Multithread Hello Server (Short Form) import java.io.*; import java.net.*; public class ThreadingHelloServer2 { public static void main(String[] args) throws Exception { ServerSocket server = new ServerSocket(12345); System.out.println(&quot;Server is started&quot;); while(true) { final Socket socket = server.accept(); Thread t = new Thread() { public void run() { try { DataInputStream dis = new DataInputStream(socket.getInputStream()); DataOutputStream dos = new DataOutputStream(socket.getOutputStream()); String name = dis.readUTF(); System.out.println(&quot;I see &quot; + name); for (int i = 0 ; i < 10 ; i++) { Thread.sleep(1000); System.out.println(&quot;Delay for &quot; + name + &quot; #&quot; + i); } dos.writeUTF(&quot;Hello &quot; + name); socket.close(); } catch(Exception ex) { ex.printStackTrace(); } }}; t.start(); }}}
  • 26. The End Any Questions?