Socket Programming (in Java)

  • June 2020
  • PDF

This document was uploaded by user and they confirmed that they have the permission to share it. If you are author or own the copyright of this book, please report to us by using this DMCA report form. Report DMCA


Overview

Download & View Socket Programming (in Java) as PDF for free.

More details

  • Words: 1,959
  • Pages: 26
Socket Programming (in Java) ELG/CEG 4183 - February 2003 by Natalija Vlajic

Web References http://java.sun.com/docs/books/tutorial/networking/overview/networking.html http://systems.cs.colorado.edu/grunwald/NetworksResources/Slides/JavaNetworkProgramming.ppt

1

Networking Basics

• computers running on the Internet communicate to each other using either Transmission Control (TCP) or the User Datagram (UDP) protocol • when we write Java programs that communicate over the network, we are programming at the application layer • however, to decide which Java classes our programs should use, we need to understand how TCP and UDP differ 2

UDP (User Datagram Protocol) • connectionless - sends independent packets of data, called datagrams, from one computer to another with no guarantees about arrival • each time a datagram is sent, the local and receiving socket address need to be sent as well

TCP (Transmission Control Protocol) • connection-oriented - provides a reliable flow of data between two computers  data sent from one end of the connection gets to the other end in the same order

• in order to communicate using TCP protocol, a connection must first be established between the pair of sockets • once two sockets have been connected, they can be used to transmit data in both (or either one of the) directions 3

UDP vs. TCP: Which Protocol to Use? • Overhead  UDP - every time a datagram is sent, the local and receiving socket address need to be sent along with it  TCP - a connection must be established before communications between the pair of sockets start (i.e. there is a connection setup time in TCP)

• Packet Size  UDP - there is a size limit of 64 kilobytes per datagram  TCP - there is no limit; the pair of sockets behaves like streams

• Reliability  UDP - there is no guarantee that the sent datagrams will be received in the same order by the receiving socket  TCP - it is guaranteed that the sent packets will be received in the order in which they were sent 4

UDP vs. TCP: Which Protocol to Use? (cont.) • TCP - useful when indefinite amount of data of need to be transferred ‘in order’ and reliably  otherwise, we end up with jumbled files or invalid information  examples: HTTP, ftp, telnet, …

• UDP - useful when data transfer should not be slowed down by the extra overhead of the reliable connection  examples: real-time applications  e.g. consider a clock server that sends the current time to its client  if the client misses a packet, it doesn't make sense to resend it because the time will be incorrect when the client receives it on the second try  the reliability of TCP is unnecessary -it might cause performance degradation and hinder the usefulness of the service 5

Some Internet Application and their Underlying Transport Protocols Application

Application Protocol

Transport Protocol

e-mail remote access Web file transfer

smtp telnet http ftp

TCP TCP TCP TCP

streaming media domain name service

proprietary DNS

TCP or UDP TCP or UDP

internet telephony

proprietary

UDP

6

What is a Port?

• generally, a computer has a single physical connection to the network  this connection is identified by the computer’s 32-bit IP address  all data destined for a particular computer arrives through this connection

• TCP and UDP use ports to identify a particular process/application  port = abstract destination point at a particular host  each port is identified by a positive 16-bit number, in the range 0 - 65,535  port numbers 0 - 1023 are reserved for well-known services (HTTP - 80, telnet - 23)

7

What is a Socket? process A write

network

read

process B write read

sockets (IP_address + port)

• socket = basic abstraction for network communication  “end-point of communication” uniquely identified with IP address and port  example: Socket MyClient = new Socket("Machine name", PortNumber);

 gives a file-system like abstraction to the capabilities of the network  two end-points communicate by “writing” into and “reading” out of socket

 there are two types of transport via sockets  reliable, byte-stream oriented  unreliable datagram

8

Socket Programming with TCP Server Side:  server runs on a specific computer and has a socket bound to a specific port number  server listens to the socket for a client to make a connection request

Client Server (running)

Client

Client Side:  client tries to rendezvous with the server on the server's machine and port

Client

Server Side:

Client

 the server accepts the connection by creating a new socket bound to a different port

Client Side:  if the connection is accepted, the client uses the new socket to communicate with the server

Server (running)

Client

Client

9

Socket Programming with TCP (cont.) Server (running)

Client

create socket for incoming requests welcomeSocket = new ServerSocket()

wait for incoming requests

TCP connection setup

create new socket connectionSocket = welcomeSocket.accept()

read request from connectionSocket

create socket, connect to server clientSocket = new Socket()

send request using clientSocket

write reply to connectionSocket read reply from clientSocket close connectionSocket

close clientSocket

10

Socket Programming with UDP • all clients use the same socket to communicate with the server  packets of data (datagrams) are exchanged  no new sockets need to be created

Client Server (running)

Client

Client

11

Socket Programming with UDP (cont.) Server (running)

create socket for incoming datagrams serverSocket = new DatagramSocket()

read datagram from connectionSocket

write reply to connectionSocket specifying client’s host address & port number

Client

create socket clientSocket = new DatagramSocket()

create, address and send datagram using clientSocket

read reply from clientSocket

close clientSocket

12

C- vs. Java- Socket Programming

C code to establish a socket

Java code to establish a socket

int set_up_socket(u_short port) { char myname[MAXHOSTNAME+1]; int s; struct sockaddr_in sa; struct hostent *he; bzero(&sa,sizeof(struct sockaddr_in)); gethostname(myname,MAXHOSTNAME); he= gethostbyname(myname); if (he == NULL) return(-1); sa.sin_family= he->h_addrtype; sa.sin_port= htons(port); if ((s= socket(AF_INET,SOCK_STREAM,0)) <0) return(-1); if (bind(s, &sa, sizeof(sa), 0) < 0) { close(s); return(-1); } listen(s, 3); return(s); }

/* /* /* /*

clear the address */ establish identity */ get our address */ if addr not found... */

/* host address */ /* port number */ /* finally, create socket */

/* bind address to socket */ /* max queued connections */

ServerSocket servsock = new ServerSocket(port, 3); 13

C- vs. Java- Socket Programming (cont.) • Java keeps all the socket complexity “under the cover”  it does not expose the full range of socket possibilities  but, it enables that sockets be opened/used as easily as a file would be opened/ used

• by using the java.net.Socket class instead of relying on native code, Java programs can communicate over the network in a platform-independent fashion

14

Java Socket Programming • all classes related to sockets are in java.net package  Socket class

-

implements client sockets (also called just "sockets")

 ServerSocket class

-

implements server sockets

A server socket waits for requests to come in over the network. It performs some operation based on that request, and then possibly returns a result to the requester.

 DatagramSocket class

-

socket for sending and receiving datagram packets

 DatagramPacket class

-

represents a datagram packet

Datagram packets are used to implement a connectionless packet delivery service. Multiple packets sent from one machine to another might be routed differently, and might arrive in any order.

 InetAddress class

-

represents an Internet Protocol (IP) address

 MulticastSocket class

-

useful for sending and receiving IP multicast packets.

A MulticastSocket is a (UDP) DatagramSocket, with additional capabilities for joining "groups" of other multicast hosts on the internet. A multicast group is specified by a class D IP address.

15

Java Client/Server Example  a client reads a line from its standard input (keyboard) and sends the line to the server  the server reads the line  the server converts the line to uppercase  the server sends the modified line back to the client  the client reads the modified line, and prints the line on its standard output

Implement above client/server scenario using both TCP and UDP!

16

Socket Programming with TCP Server (running)

Client

create socket for incoming requests welcomeSocket = new ServerSocket()

wait for incoming requests

TCP connection setup

create new socket connectionSocket = welcomeSocket.accept()

read request from connectionSocket

create socket, connect to server clientSocket = new Socket()

send request using clientSocket

write reply to connectionSocket read reply from clientSocket close connectionSocket

close clientSocket

17

Java TCP-Server (TCP Echo Server) import java.io.*; import java.net.*; class TCPServer { public static void main (String argv[]) throws Exception { String clientSentence; String capitalizedSentence; create createwelcoming welcoming socket socketat atport port5555 5555 wait waitfor forcontactcontactrequest requestby byclients clients once onceaarequest requestarrives, arrives, allocate allocatenew newsocket socket

create create&&attach attachinput input stream to new socket stream to new socket

ServerSocket welcomeSocket = new ServerSocket(5555); while(true) { Socket connectionSocket = welcomeSocket.accept(); BufferedReader inFromClient = new BufferedReader (new InputStreamReader(connectionSocket.getInputStream())); 18

Java TCP-Server (cont.) create create&&attach attachoutput output stream to new socket stream to new socket

DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream()); clientSentence = inFromClient.readLine();

read readfrom fromsocket socket

capitalizedSentence = clientSentence.toUpperCase() + ‘\n’; outToClient.writeBytes(capitalizedSentence);

write writeto tosocket socket

}

}

}

end endof ofwhile whileloop loop–– wait for another wait for another client clientto toconnect connect

19

Java TCP-Client import java.io.*; import java.net.*; class TCPClient { public static void main (String argv[]) throws Exception { String sentence; String modifiedSentence; create createinput inputstream stream

create createclient clientsocket; socket; connect connectto toserver server

create createoutput outputstream stream attached attachedto tosocket socket

BufferedReader inFromUser = new BufferedReader (new InputStreamReader(System.in)); Socket clientSocket = new Socket(“hostname”,5555); DataOutputStream outToServer = new DataOutputStream (clientSocket.getOutputStream());

20

Java TCP-Client (cont.) BufferedReader inFromServer = new BufferedReader (new InputStreamReader(clientSocket.getInputStream()));

create createinput inputstream stream attached attachedto tosocket socket

sentence = inFromUser.readLine(); outToServer.writeBytes(sentence + ‘\n’);

send sendline lineto toserver server

modifiedSentence = inFromServer.readLine(); System.out.println(“FROM SERVER: “+modifiedSentence);

read readline linefrom fromserver server

clientSocket.close(); }

}

21

Socket Programming with UDP Server (running)

create socket for incoming datagrams serverSocket = new DatagramSocket()

read datagram from connectionSocket

write reply to connectionSocket specifying client’s host address & port number

Client

create socket clientSocket = new DatagramSocket()

create, address and send datagram using clientSocket

read reply from clientSocket

close clientSocket

22

Java UDP-Server (UDP Echo Server) import java.io.*; import java.net.*; class UDPServer { public static void main (String argv[]) throws Exception { create createdatagram datagram socket at socket atport port5555 5555

DatagramSocket serverSocket = new DatagramSocket(7777); byte[] receiveData = new byte[1024]; byte[] sendData = new byte[1024]; while(true) {

create createspace spacefor for received receiveddatagram datagram

DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);

receive receivedatagram datagram

serverSocket.receive(receivePacket); 23

Java UDP-Server (cont.) String sentence = new String(receivePacket.getData()); get getIP IPaddress address of the sender of the sender

InetAddress IPAddress = receivePacket.getAddress(); int port = receivePacket.getPort();

get getport portnumber number of the of thesender sender

String capitalizedSentence = sentence.toUpperCase() + ‘\n’; sendData = capitalizedSentence.getBytes();

create createdatagram datagram to tosend sendto toclient client

DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length,IPAddress,port);

write writedatagram datagram to tosocket socket loop loopback backand and wait for wait foranother another datagram datagram

}

serverSocket.send(sendPacket); }

}

24

Java UDP-Client import java.io.*; import java.net.*; class UDPClient { public static void main (String argv[]) throws Exception { create createinput inputstream stream

create createclient clientsocket socket

translate translatehostname hostnameto to IP address IP address

BufferedReader inFromUser = new BufferedReader (new InputStreamReader(System.in)); DatagramSocket clientSocket = new DatagramSocket(); InetAddress IPAddress = InetAddress.getByName(“localhost”); byte[] sendData = new byte[1204]; byte[] receiveData = new byte[1204]; String sentence = inFromUser.readLine(); sendData = sentence.getBytes();

25

Java UDP-Client (cont.) DatagramPacket sendPacket = new DatagramPacket(sendData,sendData.length,IPAddress,7777);

create createdatagram datagramwith with data, data,length, length, IP IPadd., add.,port portnumber number

clientSocket.send(sendPacket);

send senddatagram datagram

DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length); clientSocket.receive(receivePacket);

read readdatagram datagram

String modifiedSentence = new String(receivePacket.getData()); System.out.println(“FROM SERVER: “+modifiedSentence.trim()); clientSocket.close(); }

}

26

Related Documents

Socket Programming
June 2020 9
Socket Programming
October 2019 24
Socket Programming
November 2019 22
C Socket Programming
November 2019 18