Download presentation
Presentation is loading. Please wait.
Published byMoris Matthews Modified over 9 years ago
1
Socket-Programming
2
Establish contact (connection). Exchange information (bi-directional). Terminate contact.
3
3 Network Request Result a client, a server, and network Client Server Client machine Server machine
4
Other examples: Chatroom
5
Connection-oriented Setup the link before communication. Similar to the phone call. We need the phone number and receiver. Connectionless No link needed to be set up before communication. Similar to send a letter. We need the address and receiver.
6
6 UDP (User Datagram Protocol) is a protocol that sends independent packets of data, called datagrams, from one computer to another with no guarantees about arrival. Example applications: Clock server Ping TCP/IP Stack Application (http,ftp,telnet,…) Transport (TCP, UDP,..) Network (IP,..) Link (device driver,..)
7
7 The TCP and UDP protocols use ports to map incoming data to a particular process running on a computer. server PORT PORT Client TCP TCP or UDP port app port#data Data Packet
8
Figure 2.6-2: Client socket, welcoming socket and connection socket
9
Server waits for client to request a connection. Client contacts server to establish a connection. Client sends request. Server sends reply. Client and/or server terminate connection.
10
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)
11
Some “well-known” ports: 21: ftp 23: telnet 80: http 161: snmp Check out /etc/services file for complete list of ports and services associated to those ports Port numbers between 0.. 1023 are reserved User level process/services generally use port number value >= 1024
12
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 Socket Programming with UDP No need for a welcoming socket. No streams are attached to the sockets. the sending hosts creates “packets” by attaching the IP destination address and port number to each batch of bytes. The receiving process must unravel to received packet to obtain the packet’s information bytes.
13
SOCK_STREAM TCP connection oriented, bidirectional reliable, in-order delivery SOCK_DGRAM UDP no connection unreliable delivery, no guarantee on the order can send/receive
14
socket() connect() send() recv() close()... socket() bind() listen() accept() recv() send() close() wait for connection request from next client Client Server
16
The package java.net provides support for sockets programming (and more). Typically you import everything defined in this package with: import java.net.*; Java Socket Programming 16
17
The Java API provides datagram communication by means of two classes: DatagramPacket - Datagram packets are used to implement a connectionless packet delivery service. DatagramSocket - A datagram socket is the sending or receiving point for a packet delivery service. DatagramPacket: getData - Returns the data buffer. getPort - Returns the port number on the remote host. getAddress - Returns the IP address.
18
DatagramSocket: send - Sends a datagram packet from this socket. receive - Receives a datagram packet from this socket. setSoTimeout - Enable/disable the specified timeout, in milliseconds. connect - Connects the socket to a remote address for this socket.
19
InetAddress Socket ServerSocket DatagramSocket DatagramPacket Java Socket Programming 19
20
DatagramSocket class DatagramPacket class needed to specify the payload incoming or outgoing Java Socket Programming 20
21
In Package java.net java.net.DatagramSocket A socket for sending and receiving datagram packets. Constructor and Methods DatagramSocket(int port): Constructs a datagram socket and binds it to the specified port on the local host machine. void receive( DatagramPacket p) void send( DatagramPacket p) void close() Java Socket Programming 21
22
DatagramSocket(); DatagramSocket(int port); DatagramSocket(int port, InetAddress a); All can throw SocketException or SecurityException Java Socket Programming 22
23
void connect(InetAddress, int port); void close(); void receive(DatagramPacket p); void send(DatagramPacket p); Java Socket Programming 23
24
Contain the payload (a byte array Can also be used to specify the destination address when not using connected mode UDP Java Socket Programming 24
25
For receiving: DatagramPacket( byte[] buf, int len); For sending: DatagramPacket( byte[] buf, int len InetAddress a, int port); Java Socket Programming 25
26
Corresponds to active TCP sockets only! client sockets socket returned by accept(); Passive sockets are supported by a different class: ServerSocket UDP sockets are supported by DatagramSocket Java Socket Programming 26
27
CPSC 441 - Application Layer 27 Client process client TCP socket Stream 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, e.g., keyboard or socket. An output stream is attached to an output source, e.g., monitor or socket.
28
close clientSocket Server (running on hostid) read reply from clientSocket create socket, clientSocket = DatagramSocket() Client Create, address (hostid, port=x, send datagram request using clientSocket create socket, port=x, for incoming request: serverSocket = DatagramSocket() read request from serverSocket write reply to serverSocket specifying client host address, port umber
29
CPSC 441 - Application Layer 29 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
30
30 A server (program) runs on a specific computer and has a socket that is bound to a specific port. The server waits and listens to the socket for a client to make a connection request. server Client Connection request port
31
31 If everything goes well, the server accepts the connection. Upon acceptance, the server gets a new socket bounds to a different port. It needs a new socket (consequently a different port number) so that it can continue to listen to the original socket for connection requests while serving the connected client. server Client Connection port
32
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)
33
In Package java.net java.net.DatagramSocket A socket for sending and receiving datagram packets. Constructor and Methods DatagramSocket(int port): Constructs a datagram socket and binds it to the specified port on the local host machine. void receive( DatagramPacket p) void send( DatagramPacket p) void close()
34
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 byte[1024]; byte[] receiveData = new byte[1024]; String sentence = inFromUser.readLine(); sendData = sentence.getBytes();
35
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 9876); clientSocket.send(sendPacket); DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length); clientSocket.receive(receivePacket); String modifiedSentence = new String(receivePacket.getData()); System.out.println("FROM SERVER:" + modifiedSentence); clientSocket.close(); } }
36
import java.io.*; import java.net.*; class UDPServer { public static void main(String args[]) throws Exception { DatagramSocket serverSocket = new DatagramSocket(9876); byte[] receiveData = new byte[1024]; byte[] sendData = new byte[1024]; while(true) { DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length); serverSocket.receive(receivePacket); String sentence = new String(receivePacket.getData());
37
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(sendPacket); }
38
38 1. Open the Server Socket: ServerSocket server; DataOutputStream os; DataInputStream is; server = new ServerSocket( PORT ); 2. Wait for the Client Request: Socket client = server.accept(); 3. Create I/O streams for communicating to the client is = new DataInputStream( client.getInputStream() ); os = new DataOutputStream( client.getOutputStream() ); 4. Perform communication with client Receive from client: String line = is.readLine(); Send to client: os.writeBytes("Hello\n"); 5. Close sockets: client.close(); For multithreaded server: while(true) { i. wait for client requests (step 2 above) ii. create a thread with “ client ” socket as parameter (the thread creates streams (as in step (3) and does communication as stated in (4). Remove thread once service is provided. }
39
39 1. Create a Socket Object: client = new Socket( server, port_id ); 2. Create I/O streams for communicating with the server. is = new DataInputStream(client.getInputStream() ); os = new DataOutputStream( client.getOutputStream() ); 3. Perform I/O or communication with the server: Receive data from the server: String line = is.readLine(); Send data to the server: os.writeBytes("Hello\n"); 4. Close the socket when done: client.close();
40
40 // SimpleServer.java: a simple server program import java.net.*; import java.io.*; public class SimpleServer { public static void main(String args[]) throws IOException { // Register service on port 1234 ServerSocket s = new ServerSocket(1234); Socket s1=s.accept(); // Wait and accept a connection // Get a communication stream associated with the socket OutputStream s1out = s1.getOutputStream(); DataOutputStream dos = new DataOutputStream (s1out); // Send a string! dos.writeUTF("Hi there"); // Close the connection, but not the server socket dos.close(); s1out.close(); s1.close(); }
41
41 // SimpleClient.java: a simple client program import java.net.*; import java.io.*; public class SimpleClient { public static void main(String args[]) throws IOException { // Open your connection to a server, at port 1234 Socket s1 = new Socket("mundroo.cs.mu.oz.au",1234); // Get an input file handle from the socket and read the input InputStream s1In = s1.getInputStream(); DataInputStream dis = new DataInputStream(s1In); String st = new String (dis.readUTF()); System.out.println(st); // When done, just close the connection and exit dis.close(); s1In.close(); s1.close(); }
42
42 Run Server on mundroo.cs.mu.oz.au [raj@mundroo] java SimpleServer & Run Client on any machine (including mundroo): [raj@mundroo] java SimpleClient Hi there If you run client when server is not up: [raj@mundroo] sockets [1:147] java SimpleClient Exception in thread "main" java.net.ConnectException: Connection refused at java.net.PlainSocketImpl.socketConnect(Native Method) at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:320) at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:133) at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:120) at java.net.Socket. (Socket.java:273) at java.net.Socket. (Socket.java:100) at SimpleClient.main(SimpleClient.java:6)
43
43 A socket is an endpoint of a two-way communication link between two programs running on the network. A socket is bound to a port number so that the TCP layer can identify the application that data destined to be sent. Java’s.net package provides two classes: Socket – for implementing a client ServerSocket – for implementing a server
44
44 1. Open the Server Socket: ServerSocket server; DataOutputStream os; DataInputStream is; server = new ServerSocket( PORT ); 2. Wait for the Client Request: Socket client = server.accept(); 3. Create I/O streams for communicating to the client is = new DataInputStream( client.getInputStream() ); os = new DataOutputStream( client.getOutputStream() ); 4. Perform communication with client Receive from client: String line = is.readLine(); Send to client: os.writeBytes("Hello\n"); 5. Close sockets: client.close(); For multithreaded server: while(true) { i. wait for client requests (step 2 above) ii. create a thread with “ client ” socket as parameter (the thread creates streams (as in step (3) and does communication as stated in (4). Remove thread once service is provided. }
45
45 1. Create a Socket Object: client = new Socket( server, port_id ); 2. Create I/O streams for communicating with the server. is = new DataInputStream(client.getInputStream() ); os = new DataOutputStream( client.getOutputStream() ); 3. Perform I/O or communication with the server: Receive data from the server: String line = is.readLine(); Send data to the server: os.writeBytes("Hello\n"); 4. Close the socket when done: client.close();
46
46 // SimpleServer.java: a simple server program import java.net.*; import java.io.*; public class SimpleServer { public static void main(String args[]) throws IOException { // Register service on port 1234 ServerSocket s = new ServerSocket(1234); Socket s1=s.accept(); // Wait and accept a connection // Get a communication stream associated with the socket OutputStream s1out = s1.getOutputStream(); DataOutputStream dos = new DataOutputStream (s1out); // Send a string! dos.writeUTF("Hi there"); // Close the connection, but not the server socket dos.close(); s1out.close(); s1.close(); }
47
47 // SimpleClient.java: a simple client program import java.net.*; import java.io.*; public class SimpleClient { public static void main(String args[]) throws IOException { // Open your connection to a server, at port 1234 Socket s1 = new Socket("mundroo.cs.mu.oz.au",1234); // Get an input file handle from the socket and read the input InputStream s1In = s1.getInputStream(); DataInputStream dis = new DataInputStream(s1In); String st = new String (dis.readUTF()); System.out.println(st); // When done, just close the connection and exit dis.close(); s1In.close(); s1.close(); }
48
48 Run Server on mundroo.cs.mu.oz.au [raj@mundroo] java SimpleServer & Run Client on any machine (including mundroo): [raj@mundroo] java SimpleClient Hi there If you run client when server is not up: [raj@mundroo] sockets [1:147] java SimpleClient Exception in thread "main" java.net.ConnectException: Connection refused at java.net.PlainSocketImpl.socketConnect(Native Method) at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:320) at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:133) at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:120) at java.net.Socket. (Socket.java:273) at java.net.Socket. (Socket.java:100) at SimpleClient.main(SimpleClient.java:6)
49
49 TCP (Transport Control Protocol) is a connection- oriented protocol that provides a reliable flow of data between two computers. Example applications: HTTP FTP Telnet TCP/IP Stack Application (http,ftp,telnet,…) Transport (TCP, UDP,..) Network (IP,..) Link (device driver,..)
Similar presentations
© 2024 SlidePlayer.com Inc.
All rights reserved.