Socket Programming* - PowerPoint PPT Presentation

1 / 37
About This Presentation
Title:

Socket Programming*

Description:

new BufferedReader(new InputStreamReader(System.in) ... Try A New Example ... Modify TCPServer.java. Modify TCPClient.java. Compile. Launch TCPServer ... – PowerPoint PPT presentation

Number of Views:127
Avg rating:3.0/5.0
Slides: 38
Provided by: cseYed
Category:

less

Transcript and Presenter's Notes

Title: Socket Programming*


1
Socket Programming
  • T.A. Mustafa MISIR (http//cse.yeditepe.edu.tr/mm
    isir/s2008/cse471)
  • Modified version of a socket programming
    related presentation by Vijayanand Bharadwaj _at_
    West Virginia University based on Computer
    Networking A Top-Down Approach Featuring the
    Internet, James Kurose and Keith Ross.

2
Overview
  • Sockets What are they?
  • Sockets How do they work?
  • Sockets How to use them?
  • Sockets Sample Programs

3
Sockets What are they?
  • Network computing involves working with programs
    running on remote hosts
  • Need to communicate with those programs
  • Some terms
  • Host a node consisting of all hardware and
    software on which programs run.
  • Process a running program
  • Multiple processes can run on one host

4
Sockets What are they?
  • Processes on same host communicate through
    inter-process communication, defined by the
    operating system.
  • How do processes on different hosts communicate?

5
Sockets What are they?
  • Processes on remote hosts use messages to
    communicate.
  • Client process process that initiates
    communication
  • Server process process that waits to be
    contacted
  • Clients and Servers use sockets to communicate

6
Sockets What are they?
  • Process sends/receives messages to/from its
    socket
  • Socket is analogous to door, electrical wall
    socket
  • sending process shoves message out door
  • sending process relies on transport
    infrastructure on other side of door which brings
    message to socket at receiving process

7
Sockets What are they?
user
application
Internet
8
Sockets What are they?
  • Applications interface with the transport layer
    using sockets.
  • This interface is implemented through an
    Application Programming Interface (API)
  • i.e. applications can programmatically create and
    use sockets.
  • Thus physically, a socket is a software
    interface. More formally
  • -- a host-local, application-created,
    OS-controlled interface (a door) into which
    application process can both send and receive
    messages to/from another application process.

9
TCP vs. UDP
10
TCP vs. UDP (cont.)
11
Sockets Sample Programs
  • Socket programming with
  • TCP
  • UDP
  • Java Socket API
  • Object-Oriented encapsulates most of the details
    into objects.
  • Simple compared to the BSD Sockets API

12
Sockets Sample Programs
  • Socket programming with
  • TCP
  • UDP
  • Java Socket API
  • Object-Oriented encapsulates most of the details
    into objects.
  • Simple compared to the BSD Sockets API

13
Socket-programming with TCP
  • TCP service reliable transfer of bytes from one
    process to another

controlled by application developer
controlled by application developer
controlled by operating system
controlled by operating system
internet
host or server
host or server
14
Socket-programming with TCP
  • Client must contact server
  • Server process must first be running
  • Server must have created socket (door) that
    welcomes clients contact
  • Client contacts server by
  • Creating client-local TCP socket
  • Specifying IP address, port number of server
    process
  • When client creates socket client TCP
    establishes connection to server TCP

15
Socket-programming with TCP
  • When contacted by client, server TCP creates new
    socket for server process to communicate with
    client
  • allows server to talk with multiple clients
  • source port numbers used to distinguish clients

16
Stream jargon
  • A stream is a sequence of characters that flow
    into or out of a process.
  • An input stream is attached to some input source
    for the process, eg, keyboard or socket.
  • An output stream is attached to an output source,
    eg, monitor or socket.

17
Socket programming with TCP
  • Example client-server application
  • 1) Client reads line from standard input
    (inFromUser stream) , sends to server via socket
    (outToServer stream)
  • 2) Server reads line from socket
  • 3) Server converts line to uppercase, sends back
    to client
  • 4) Client reads, prints modified line from
    socket (inFromServer stream)

18
Socket programming with TCP
Client process
client TCP socket
19
Client/server socket interaction TCP
Server (running on hostid)
Client
20
Example Java client (TCP)
import java.io. import java.net. class
TCPClient public static void main(String
argv) throws Exception String
sentence String modifiedSentence
BufferedReader inFromUser new
BufferedReader(new InputStreamReader(System.in))
Socket clientSocket new
Socket("hostname", 6789)
DataOutputStream outToServer new
DataOutputStream(clientSocket.getOutputStream())

Create input stream
Create client socket, connect to server
Create output stream attached to socket
21
Example Java client (TCP), cont.
Create input stream attached to socket
BufferedReader inFromServer
new BufferedReader(new
InputStreamReader(clientSocket.getInputStream()))
sentence inFromUser.readLine()
outToServer.writeBytes(sentence '\n')
modifiedSentence inFromServer.readLine()
System.out.println("FROM SERVER "
modifiedSentence) clientSocket.close()

Send line to server
Read line from server
22
Example Java server (TCP)
import java.io. import java.net. class
TCPServer public static void main(String
argv) throws Exception String
clientSentence String capitalizedSentence
ServerSocket welcomeSocket new
ServerSocket(6789) while(true)
Socket connectionSocket
welcomeSocket.accept()
BufferedReader inFromClient new
BufferedReader(new
InputStreamReader(connectionSocket.getInputStream(
)))
Create welcoming socket at port 6789
Wait, on welcoming socket for contact by client
Create input stream, attached to socket
23
Example Java server (TCP), cont
DataOutputStream outToClient
new DataOutputStream(connectionSocket.get
OutputStream()) clientSentence
inFromClient.readLine()
capitalizedSentence clientSentence.toUpperCase()
'\n' outToClient.writeBytes(capit
alizedSentence)
Create output stream, attached to socket
Read in line from socket
Write out line to socket
End of while loop, loop back and wait for another
client connection
24
Socket programming with UDP
  • UDP no connection between client and server
  • no handshaking
  • sender explicitly attaches IP address and port of
    destination to each packet
  • server must extract IP address, port of sender
    from received packet
  • UDP transmitted data may be received out of
    order, or lost

25
Client/server socket interaction UDP
Server (running on hostid)
26
Example Java client (UDP)
Client process
Input receives packet (TCP received byte
stream)
Output sends packet (TCP sent byte stream)
client UDP socket
27
Example Java client (UDP)
import java.io. import java.net. class
UDPClient public static void main(String
args) throws Exception
BufferedReader inFromUser new
BufferedReader(new InputStreamReader(System.in))
DatagramSocket clientSocket new
DatagramSocket() InetAddress IPAddress
InetAddress.getByName("hostname")
byte sendData new byte1024 byte
receiveData new byte1024 String
sentence inFromUser.readLine() sendData
sentence.getBytes()
Create input stream
Create client socket
Translate hostname to IP address using DNS
28
Example Java client (UDP), cont.
Create datagram with data-to-send, length, IP
addr, port
DatagramPacket sendPacket new
DatagramPacket(sendData, sendData.length,
IPAddress, 9876) clientSocket.send(send
Packet) DatagramPacket receivePacket
new DatagramPacket(receiveData,
receiveData.length) clientSocket.receiv
e(receivePacket) String
modifiedSentence new
String(receivePacket.getData())
System.out.println("FROM SERVER"
modifiedSentence) clientSocket.close()

Send datagram to server
Read datagram from server
29
Example Java server (UDP)
import java.io. import java.net. class
UDPServer public static void main(String
args) throws Exception
DatagramSocket serverSocket new
DatagramSocket(9876) byte
receiveData new byte1024 byte
sendData new byte1024 while(true)
DatagramPacket
receivePacket new
DatagramPacket(receiveData, receiveData.length)
serverSocket.receive(receivePacket)
Create datagram socket at port 9876
Create space for received datagram
Receive datagram
30
Example Java server (UDP), cont
String sentence new
String(receivePacket.getData())
InetAddress IPAddress receivePacket.getAddress()
int port receivePacket.getPort()
String
capitalizedSentence sentence.toUpperCase()
sendData capitalizedSentence.getBytes()
DatagramPacket sendPacket
new DatagramPacket(sendData,
sendData.length, IPAddress,
port) serverSocket.send(s
endPacket)
Get IP addr port , of sender
Create datagram to send to client
Write out datagram to socket
End of while loop, loop back and wait for another
datagram
31
Points to Remember
  • A host has an IP addresses
  • Can have multiple IP addresses. Actually each
    interface has an IP Address.
  • Many applications can run on a host.
  • Each application is identified by a port number
  • An application can be made up of many processes.

32
Points to Remember
  • Processes communicate using Sockets
  • One process can have multiple sockets
  • Example. TCPServer.java
  • All sockets share the same port number !!
  • But why no BIND EXCEPTION !!!!
  • We will see next section !!
  • Multiple processes can share a single socket !!
  • Example. An application where multiple processes
    take turns communicating using the same socket
  • Application developer needs to synchronize access
    to Socket.

33
Points to Remember
  • An example Multi-Threaded Web Server
  • The original process listens on one socket (
    welcomeSocket) and creates multiple dedicated
    sockets for each client that contacts it.
    Original socket bound to port 80.
  • Creates a process to deal with each client and
    assigns it the newly created socket.
  • All sockets are bound to port 80 !!
  • Very Similar Example is the KKMultiServer.java
    and KKMultiServerThread.java on SUNs official
    Java tutorial web site
  • http//java.sun.com/docs/books/tutorial/networking
    /sockets/clientServer.html

34
Points to Remember
  • Try A New Example ...
  • Modify TCPServer.java
  • Modify TCPClient.java
  • Compile
  • Launch TCPServer
  • Launch TCPClient

35
Points to Remember
  • PROMPTgtjava TCPServer
  • Server Socket's IP Address localhost/127.0.0.1
  • Server Socket's Port Number 6789
  • Connection Socket's IP Address /127.0.0.1
  • Connection Socket's Port Number 6789
  • Connection Socket's Remote IP Address
    /127.0.0.1
  • Connection Socket's Remote Port Number 1796
  • PROMPTgtjava TCPClient
  • Client Socket's IP Address /127.0.0.1
  • Client Socket's Port Number 1796
  • Hello There!
  • FROM SERVER HELLO THERE!
  • Same Port Numbers Used by both Sockets!

36
Points to Remember
  • Run TCPServer Again from another prompt !
  • BIND EXCEPTION !!!
  • PROMPTgtjava TCPServer
  • Exception in thread "main" java.net.BindException
    Address already in use JVM_Bind
  • at java.net.PlainSocketImpl.socketBind(Nat
    ive Method)
  • at java.net.PlainSocketImpl.bind(Unknown
    Source)
  • at java.net.ServerSocket.bind(Unknown
    Source)
  • at java.net.ServerSocket.ltinitgt(Unknown
    Source)
  • at java.net.ServerSocket.ltinitgt(Unknown
    Source)
  • at TCPServer.main(TCPServer.java11)

37
WHY IS THIS BEHAVIOR ???
  • When Transport Layer handles Sockets it manages
    them by assigning UNIQUE IDENTIFIERS to each
    socket it creates.
  • Thus sockets can share port numbers since
    Transport Layer uses the port number as one piece
    of the socket identifier
  • However when the application layer tries to bind
    more than one socket to a port, transport throws
    an EXCEPTION !!!
Write a Comment
User Comments (0)
About PowerShow.com