JAVA Socket Programming: 2003.3.19 Joonbok Lee Kaist
JAVA Socket Programming: 2003.3.19 Joonbok Lee Kaist
2003.3.19
Joonbok Lee
KAIST
What is a socket?
• Socket
– The combination of an IP address and a port number. (RFC 793
,original TCP specification)
– The name of the Berkeley-derived application programming
interfaces (APIs) for applications using TCP/IP protocols.
– Two types
• Stream socket : reliable two-way connected communication streams
• Datagram socket
• Socket pair
– Specified the two end points that uniquely identifies each TCP
connection in an internet.
– 4-tuple: (client IP address, client port number, server IP address,
server port number)
Client-server applications
• Implementation of a protocol standard defined in an RFC. (FTP,
HTTP, SMTP…)
– Conform to the rules dictated by the RFC.
– Should use the port number associated with the protocol.
• Client
– Client socket
• Initiate a TCP connection to the server by creating a socket
object. (Three-way handshake)
• Specify the address of the server process, namely, the IP
address of the server and the port number of the process.
Socket functional calls
• socket (): Create a socket
• bind(): bind a socket to a local IP address and port #
• listen(): passively waiting for connections
• connect(): initiating connection to another socket
• accept(): accept a new connection
• Write(): write data to a socket
• Read(): read data from a socket
• sendto(): send a datagram to another UDP socket
• recvfrom(): read a datagram from a UDP socket
• close(): close a socket (tear down the connection)
Sockets
recv( )
send( )
close( ) close( )
controlled by
application process
process
developer socket
socket
controlled by TCP with
TCP with
operating buffers, internet
system buffers,
variables
variables
Socket programming with TCP
keyboard monitor
inFromUser
input
input (inFromUser stream) , stream
inFromServer
outToServer
• client reads, prints modified output
stream
input
stream
write reply to
connectionSocket read reply from
clientSocket
close
connectionSocket close
clientSocket
JAVA TCP Sockets
• In Package java.net
– java.net.Socket
• Implements client sockets (also called just “sockets”).
• An endpoint for communication between two machines.
• Constructor and Methods
– Socket(String host, int port): Creates a stream socket and connects it to the
specified port number on the named host.
– InputStream getInputStream()
– OutputStream getOutputStream()
– close()
– java.net.ServerSocket
• Implements server sockets.
• Waits for requests to come in over the network.
• Performs some operation based on the request.
• Constructor and Methods
– ServerSocket(int port)
– Socket Accept(): Listens for a connection to be made to this socket and
accepts it. This method blocks until a connection is made.
TCPClient.java
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));
outToClient.writeBytes(capitalizedSentence);
}
}
}
Socket Programming with UDP
• UDP
– Connectionless and unreliable service.
– There isn’t an initial handshaking phase.
– Doesn’t have a pipe.
– transmitted data may be received out of order, or lost
create socket,
port=x, for create socket,
clientSocket =
incoming request: DatagramSocket()
serverSocket =
DatagramSocket()
Create, address (hostid, port=x,
send datagram request
using clientSocket
read request from
serverSocket
write reply to
serverSocket
specifying client read reply from
host address, clientSocket
port umber close
clientSocket
Example: Java client (UDP)
keyboard monitor
inFromUser
input
stream
Client
Process
Input: receives
process
packet (TCP
received “byte
Output: sends
stream”)
packet (TCP sent
receivePacket
sendPacket
“byte stream”) UDP UDP
packet packet
client
clientSocket UDP
socket UDP
socket
}
}
}
Building a Simple Web Server
• Handles only one HTTP request
• Accepts and parses the HTTP request
• Gets the required file from the server’s
file system.
• Creates an HTTP response message
consisting of the requested file
preceded by header lines
• Sends the response directly to the client
WebServer.java
import java.io.*;
import java.net.*;
import java.util.*;
class WebServer{
public static void main(String argv[]) throws Exception {
String requestMessageLine;
String fileName;
ServerSocket listenSocket = new ServerSocket(6789);
Socket connectionSocket = listenSocket.accept();
DataOutputStream outToClient =
new DataOutputStream(connectionSocket.getOutputStream());
WebServer.java
requestMessageLine = inFromClient.readLine();
StringTokenizer tokenizedLine =
new StringTokenizer(requestMessageLine);
if (tokenizedLine.nextToken().equals("GET")){
fileName = tokenizedLine.nextToken();
if (fileName.startsWith("/") == true )
fileName = fileName.substring(1);
File file = new File(fileName);
int numOfBytes = (int) file.length();
FileInputStream inFile = new FileInputStream (fileName);
byte[] fileInBytes = new byte[numOfBytes];
inFile.read(fileInBytes);
WebServer.java
outToClient.writeBytes("HTTP/1.0 200 Document Follows\r\n");
if (fileName.endsWith(".jpg"))
outToClient.writeBytes("Content-Type: image/jpeg\r\n");
if (fileName.endsWith(".gif"))
outToClient.writeBytes("Content-Type: image/gif\r\n");
outToClient.writeBytes("Content-Length: " + numOfBytes + "\r\n");
outToClient.writeBytes("\r\n");
outToClient.write(fileInBytes, 0, numOfBytes);
connectionSocket.close();
}
else System.out.println("Bad Request Message");
}
}
Concurrent server
• Servers need to handle a new
connection request while processing
previous requests.
– Most TCP servers are designed to be
concurrent.
• When a new connection request arrives
at a server, the server accepts and
invokes a new process to handle the
new client.
How to handle the port numbers
cosmos% netstat –a –n –f inet
Active Internet connections (including servers)
Proto Recv-Q Send-Q Local Address Foreign Address (state)
tcp 0 0 *.23 *.* LISTEN
Java-tutorials:
• “All About Sockets” (Sun tutorial),
http://www.javaworld.com/javaworld/jw-12-1996/jw-12-
sockets.html
• “Socket Programming in Java: a tutorial,”
http://www.javaworld.com/javaworld/jw-12-1996/jw-12-
sockets.html