5417.java tcp programming
Post on 07-Apr-2018
231 Views
Preview:
TRANSCRIPT
-
8/6/2019 5417.Java TCP Programming
1/67
Network
Programming3/23/2011
1Network Programming Rapid Application Development-CS3011
Lecture - 1
Amit Sharma
-
8/6/2019 5417.Java TCP Programming
2/67
Network Programming
Network programming is a branch of computerscience which covers the art of writingapplication programs or software that run onnetworks. These software are known as
Network Programs.3/23/2011 2Network ProgrammingRapid Application Development-CS3011
-
8/6/2019 5417.Java TCP Programming
3/67
Computer NetworkIn Tanenbaum (Author of many
networking books) words Computer Networks can be
described as an interconnectedcollection of autonomouscomputers.
Two computers are said to be interconnected, if they are able to exchange information. By theterm autonomous, it is meant that there shouldnot be any master-slave relationship between thecomputers, that is, all the computers shouldhave the resources to work independently .3/23/2011 3Network ProgrammingRapid Application Development-CS3011
-
8/6/2019 5417.Java TCP Programming
4/67
Network Programs
Send data across the network.
Provide services over a network.
Receives data over a network.
Invoke services across a network.
The main characteristics of network program is that theymust use a computer network inanyway as to perform their job.Network Programs do either of one or all of the following
3/23/2011 4Network ProgrammingRapid Application Development-CS3011
-
8/6/2019 5417.Java TCP Programming
5/67
Networking includes
Network programming includes
Reading and writing network sockets
Encryption and decryption of data
Translating network protocols
Sending data packets to other nodesProviding security to the data
And many more . . .3/23/2011 5Network ProgrammingRapid Application Development-CS3011
-
8/6/2019 5417.Java TCP Programming
6/67
What Network Programs can do
Networking extends the power of a single computer.Network lets one computer communicate withthousands, even millions, of other computers.Network may prove very efficient in the area of Electronic mailApplication ServicesInformation sharing
Parallel computingMessaging servicesWebsite programming
And many more . . .3/23/2011 6Network ProgrammingRapid Application Development-CS3011
-
8/6/2019 5417.Java TCP Programming
7/67
Client ServerModel
3/23/2011 7Network ProgrammingRapid Application Development-CS3011
Lecture - 2
Amit Sharma
-
8/6/2019 5417.Java TCP Programming
8/67
Networking ModelsFor data communication to take place, a computer
runs a program to request a service fromanother program residing on the destinationcomputer. This is the basic idea behind networkprogramming which means that two computersshould connected to the network and act as aservice requester or service provider.
It is based on, generally, two models-Client - Server ModelPeer-to-Peer Model
From which client-server model is much popularamong the network programmers.
3/23/2011 8Network ProgrammingRapid Application Development-CS3011
-
8/6/2019 5417.Java TCP Programming
9/67
Client Server Model
to whom the request is made, performs the jobfor the requesting computer. This is the basic
idea of Client-Server Model.
In a network if any hostwishes to receive aservice from a remotecomputer, it executesspecific program toperform the specific
job. Then the computer
3/23/2011 9Network ProgrammingRapid Application Development-CS3011
-
8/6/2019 5417.Java TCP Programming
10/67
Server and ClientsClient computers are those
who made requests.Server computer respond
the clients and perform
the job requested by theclient.client-server programming
requires experience withmany different technicalskills like, databaseprogramming, networkprotocols, user interfacedesign, transaction
processing, RPCs, etc.
R e q u e s t
Response
3/23/2011 10Network ProgrammingRapid Application Development-CS3011
-
8/6/2019 5417.Java TCP Programming
11/67
Client-Server Mechanism
1 1
2 2
1. REQUEST: Client initiates a connection, maderequest for the service to server.
2. RESPONSE: Server accept the request, respond
to the client and provide the services to clients.3/23/2011 11Network ProgrammingRapid Application Development-CS3011
-
8/6/2019 5417.Java TCP Programming
12/67
JavaTCP
Programming3/23/2011 12Network ProgrammingRapid Application Development-CS3011
Amit Sharma
-
8/6/2019 5417.Java TCP Programming
13/67
Transmission Control Protocol The TCP is a transport layer protocol. TCP provides reliable , full-duplex connections and
reliable service by ensuring that data is
resubmitted when transmission results in an error. TCP enables two network entities to establish a bi-
directional communications channel for readingand writing streams, that is, sequence of bytes.
The TCP protocol guarantees that bytes will bedelivered to recipient in the order written by thesender.
3/23/2011 13Network ProgrammingRapid Application Development-CS3011
-
8/6/2019 5417.Java TCP Programming
14/67
Transmission Control Protocol Once the message arrived at the correct IP
address, TCPs main task is error checking . TCP performs congestion control by
controlling the rate with which data is writtento the network in response to networkconditions.
TCP performs an additional service calledflow control .
3/23/2011 14Network ProgrammingRapid Application Development-CS3011
-
8/6/2019 5417.Java TCP Programming
15/67
Functionsof
TCP3/23/2011 15Network ProgrammingRapid Application Development-CS3011
Lecture - 3
Amit Sharma
-
8/6/2019 5417.Java TCP Programming
16/67
Stream Segmentation
Because the IP protocol only supportstransmission of limited size packets,
TCP must break the stream intosegments for transmission. In order toamortize the cost of transmitting the IP
and TCP headers, it is preferable totransmit packets containing the largestpossible payload.
3/23/2011 16Network ProgrammingRapid Application Development-CS3011
-
8/6/2019 5417.Java TCP Programming
17/67
Stream Reassembly
The TCP streams that are transmitted as IPpackets may arrive at the destination indifferent order than the order sent. TCPmust be able to handle out-of-order deliveryand still reassemble the data in the ordertransmitted. TCP addresses this problem by
counting the number of bytes transmitted inthe stream and identifying each of the firststream byte it carries.
3/23/2011 17Network ProgrammingRapid Application Development-CS3011
-
8/6/2019 5417.Java TCP Programming
18/67
Handling Packet loss IP packets carrying segments of the stream may be
lost in the way. TCP must be able to detect the factthat a packet has been lost and arrange
retransmission. TCP deletes packets loss by positive receiver
acknowledgements. When a TCP packet arrives,the receivers TCP protocol implementation will
send a TCP packet to the sender acknowledgingreceipt. If the sender fails to receiveacknowledgement by a certain deadline, it willretransmit the packet.
3/23/2011 18Network ProgrammingRapid Application Development-CS3011
-
8/6/2019 5417.Java TCP Programming
19/67
Data Corruption Detection The IP protocol only protects its own header and
does not make any guarantees on the payloadcontents. It is therefore possible that one or more bitsin the payload may be corrupted due to transmissionerror.
For this payloads summary is computed and storedin the packets header. The receiver of the packet
then independently computes the summary of thedata received, using the same algorithm andcompares it to summary stored in header. Thisalgorithm protects against all 1-bit errors and somemultiple bit errors.3/23/2011 19Network ProgrammingRapid Application Development-CS3011
-
8/6/2019 5417.Java TCP Programming
20/67
Java TCP Programming
The programming model of TCPcommunication in Java, rely
completely on the sockets and ports .Because TCP is a stream protocol, itallows to send arbitrary amount of
data rather rely on class to encapsulatedata within TCP packets.
3/23/2011 20Network ProgrammingRapid Application Development-CS3011
-
8/6/2019 5417.Java TCP Programming
21/67
Sockets
Java programs communicate through aprogramming abstraction called socket. A socketis one end-point of a two-way communicationlink between two computers (or programs)running on a network. A socket is bound to a portnumber so that the TCP layer can identify the
application that data is destined to be sent.
PORT
PORT
3/23/2011 21Network ProgrammingRapid Application Development-CS3011
-
8/6/2019 5417.Java TCP Programming
22/67
Ports
One mechanism that is commonly used by networkprotocols, and in particular the Internettransport layer protocols, is port addressing.Every network service is associated with one ormore ports on one or more IP interfaces of itshost device. Typically, integer numbers are used
to identify different ports. In order to contact anetwork service, it is therefore necessary toprovide both the IP address of its host, as well asport number it is using.
3/23/2011 22Network ProgrammingRapid Application Development-CS3011
-
8/6/2019 5417.Java TCP Programming
23/67
Stream Socket
3/23/2011 23Network ProgrammingRapid Application Development-CS3011
-
8/6/2019 5417.Java TCP Programming
24/67
Package java.net
The Java language supports TCP programmingthrough the java.net.Socket and
java.net.ServerSocket classes. Java clients
connect to TCP servers by creating instances of the java.net.Socket class . Similarly, Java serverslisten for java clients by creating
java.net.ServerSocket class. Connections areconfigured through the methods of these twoclasses. Actual network communications,however, are performed using the java.iopackage streaming classes.3/23/2011 24Network ProgrammingRapid Application Development-CS3011
-
8/6/2019 5417.Java TCP Programming
25/67
Client Program
A client is a network program residing onlocal computer, who requests for any serviceto the server. A client program is a finiteprocess which means that it is started by theuser and terminates when the service iscomplete.
For example, Web Browser is a network client which requests to the Web Server to readfiles, view images or download documents
or images on the local computer.3/23/2011 25Network ProgrammingRapid Application Development-CS3011
-
8/6/2019 5417.Java TCP Programming
26/67
Functioning of Client
A client opens the communication channel usingthe IP address of the remote host and the well-known port address of the specific servercomputer. After a channel is active, the clientsends its request and receives a response. Therequest-response part may be repeated forseveral times. At the end, the client closes the
communication channel.
SERVER CLIENTConnection
Request
PORT
3/23/2011 26Network ProgrammingRapid Application Development-CS3011
-
8/6/2019 5417.Java TCP Programming
27/67
Structure of Client ProgramClient program use TCP/IP sockets for communication
with server. The structure of basic client program is
A new socket instance is created using a constructor of Socket class.
The socket attempts to connect to a remote host, passingand IP address (or URL) and a port number.
Socket socket = new Socket(sap_server,1234);
Where sap_server is the URL and 1234 is port numberwhere it listens.
Once the client connects, the client and server interactaccording to protocol.
Finally the server, the client or both close the sockets.3/23/2011 27Network ProgrammingRapid Application Development-CS3011
-
8/6/2019 5417.Java TCP Programming
28/67
Server Program
A server is a remote computer on a network whichprovides services to the clients. When it starts,it opens the channel for incoming requests fromclients, but it never initiates a service until it isrequested to do so.
A server program is an infinite process. When it is
starts in runs infinitely unless a problemarises. It waits for incoming requests fromclients. When a request arrives, it responds tothe request either iteratively or concurrently.
3/23/2011 28Network ProgrammingRapid Application Development-CS3011
-
8/6/2019 5417.Java TCP Programming
29/67
Functioning of Server
On server side, if everything goes well, the serveraccepts the connection. Upon acceptance the severgets a new socket bound to a different port. Itneeds a new socket (and consequently a differentport number) so that it can continue to listen tothe original socket for connection requests while
tending to the needs of the connected client.
SERVER CLIENTCommunication
Channel
PORT
PORT
P O R T
3/23/2011 29Network ProgrammingRapid Application Development-CS3011
-
8/6/2019 5417.Java TCP Programming
30/67
Structure of Server ProgramThe basic steps for the coding of server program in Java are
Instance of server socket is created which listens onselected port number, using the constructors of ServerSocket class.
ServerSocket serverSocket = new ServerSocket(1234);The above code will create a serverSocket which wouldlisten on port number 1234 .This instance listens for connection on the desired port. Itwaits for client until it attempts to connect. It uses accept() method to establish the connection.Once a client connects, the accept() method returns aninstance of the socket class, which it uses as a receivingsocket. Client "sending" sockets and servers receivingsockets comes from the same Java class, Socket class.3/23/2011 30Network ProgrammingRapid Application Development-CS3011
-
8/6/2019 5417.Java TCP Programming
31/67
Structure of Server Program(Contd.)
The client and server interact according to protocol.Java servers typically use getInputStream() and getOutputStream() to handle socket communication.
Either server or client, or both close the socket.
The server returns to listening for connection on itsdesignated port.
Incoming connection requests are stored by theoperating system in a FIFO queue. Those requestswill block while the server is handing clientinteractions. But with Java, network developer canemploy a new thread to handle another client in case
of servicing the client for longer or indefinite time.3/23/2011 31Network ProgrammingRapid Application Development-CS3011
-
8/6/2019 5417.Java TCP Programming
32/67
Creating a Client Program
The java.net.Socket of a java.netpackage implements client side of a
two-way connection between Javaprogram and another program on thenetwork. By using this class instead of
relying on native code, Java programcan communicate over network inplatform independent fashion.
3/23/2011 32Network ProgrammingRapid Application Development-CS3011
-
8/6/2019 5417.Java TCP Programming
33/67
Creating a Client Socket
The java.net.Socket class provides aconstructor, which takes an IP address andport number and attempts to establish a
connection.The signature of this constructor is
Socket(InetAddress, int port)throws IOException;
Throwing the java.io.IOException exception
signals communication error.3/23/2011 33Network ProgrammingRapid Application Development-CS3011
-
8/6/2019 5417.Java TCP Programming
34/67
Creating a Client Socket
Although the signature of the constructorsonly declares the java.io.IOException ,
users can determine the reasonprogrammatically using followingsubclasses of java.io.IOException .
java.net.NoRouteToHostException java.net.ConnectException
3/23/2011 34Network ProgrammingRapid Application Development-CS3011
-
8/6/2019 5417.Java TCP Programming
35/67
Creating a Client Socket
Another constructor is provided for use withhost names, or IP addresses represented asStrings. The signature is
Socket(String host,int port)throws IOException;
This constructor may also throw an additional
IOException subclass called java.net.UnknownHostException if the hostname can not be resolved, or string
representation of the IP address is invalid.3/23/2011 35Network ProgrammingRapid Application Development-CS3011
-
8/6/2019 5417.Java TCP Programming
36/67
Creating a Client Socket
There is another equivalent constructor with theprevious constructor, which is much moreconvenient Socket(InetAddress.getByName(host),port);
3/23/2011 36Network ProgrammingRapid Application Development-CS3011
-
8/6/2019 5417.Java TCP Programming
37/67
3/23/2011 Network ProgrammingRapid Application Development-CS3011 37
Lecture - 4
Creating Clientand Server Socket
Amit Sharma
-
8/6/2019 5417.Java TCP Programming
38/67
Example demonstrating Socket Creation
import java.net.*;import java.io.*;public class SimpleClient {
public static void main(String[] args) {String host = sap_server;int port = 1234;try {
System.out.println(Attempting to connect to TCP
service on host + host + and port: + port);Socket s = new Socket(host,port);System.out.println(Connection Established . . .);
}3/23/2011 38Network ProgrammingRapid Application Development-CS3011
-
8/6/2019 5417.Java TCP Programming
39/67
Example (contd.)
catch(UnknownHostException ue) {
System.out.println(Trouble: + ue.getMessage());}catch(IOException ioe) {
System.out.println(Trouble: + ioe.getMessage());}
}}
3/23/2011 39Network ProgrammingRapid Application Development-CS3011
-
8/6/2019 5417.Java TCP Programming
40/67
Reading / Writing Socket
The Socket class provides two methods, one forobtaining an input stream for reading bytesand one for obtaining an output stream forwriting byte-stream to the output stream.
The streams are represented as java.io.InputStream java.io.OutputStream
3/23/2011 40Network ProgrammingRapid Application Development-CS3011
-
8/6/2019 5417.Java TCP Programming
41/67
Reading / Writing Socket
An exception java.io.IOException will bethrown in this case. The signatures are java.io.InputStream getInputStream()
throws IOException; java.io.OutputStream getOutputStream()
throws IOException; Once the input and output streams for the
socket have been obtained, it is up toapplication to determine the contents of
communication.3/23/2011 41Network ProgrammingRapid Application Development-CS3011
-
8/6/2019 5417.Java TCP Programming
42/67
Getting Socket Information
Connection oriented sockets may becharacterized by set:
The four methods for querying the Socket are InetAddress getInetAddress() throws IOException;int getPort() throws IOException;InetAddress getLocalAddress() throws IOException;int getLocalPort() throws IOException;
3/23/2011 42Network ProgrammingRapid Application Development-CS3011
-
8/6/2019 5417.Java TCP Programming
43/67
Terminating Socket
The close() method requests asynchronoustermination of the socket connection.
The close() method will return immediately, evenif data written before invocation has notcompleted transmission.
void close() throws IOException;
3/23/2011 43Network ProgrammingRapid Application Development-CS3011
E l ill t ti g di g/ iti g th gh S k t
-
8/6/2019 5417.Java TCP Programming
44/67
Example illustrating reading/writing through Socket/* EchoClient implements a client,, that connects to the EchoServer. The
EchoServer simply receives data from client and echoes it back. */
import java.net.*;import java.io.*;public class EchoClient {
public static void main(String[] args) {
Socket echoSocket = null;PrintWriter out = null;BufferedReader in = null;try {echoSocket = new Socket(sap_server,4444);out = new PrintWriter(echoSocket.getOutputStream(),true);
3/23/2011 44Network ProgrammingRapid Application Development-CS3011
E ample ill strating reading/ riting thro gh Socket
-
8/6/2019 5417.Java TCP Programming
45/67
Example illustrating reading/writing through Socket
in = new BufferedReader(new InputStreamReader(echoSocket.getInputStream());
} catch(UnknownHostException ue) {System.out.println(Trouble: + ue.getMessage());
} catch(IOException ioe) {
System.out.println(Trouble: + ioe.getMessage());}BufferedReader stdIn = new BufferedReader(new
InputStreamReader(System.in));
3/23/2011 45Network ProgrammingRapid Application Development-CS3011
Example illustrating reading/writing through Socket
-
8/6/2019 5417.Java TCP Programming
46/67
Example illustrating reading/writing through Socket
String userInput;while(!(userInput = stdIn.readLine()).equals(quit)) {
out.println(userInput);System.out.println(Echo: + in.readLine());
}out.close();in.close();stdIn.close();echoSocket.close();
}}
3/23/2011 46Network ProgrammingRapid Application Development-CS3011
-
8/6/2019 5417.Java TCP Programming
47/67
Server Side TCP Programming
In order to accept network connections a Javaprogram must create an instance of
java.net.ServerSocket.Server sockets are not directly used to perform
any network communication. Instead, they actas factories that create a java.net.Socket objectfor every incoming TCP communicationrequest.
Programs create the server socket, bind to aspecific port on one or more interfaces, and
then invoke the blocking accept() method.3/23/2011 47Network ProgrammingRapid Application Development-CS3011
-
8/6/2019 5417.Java TCP Programming
48/67
Creating Server Socket
The basic ServerSocket constructor takes asingle argument, the TCP port number used inbinding.
The constructor may fail due to an I/O error, ordue to a security error. The signature of theconstructor is
ServerSocket(int port) throwsIOException,SecurityException;
Port is not permitted to listen more than one
process at the same point of time.3/23/2011 48Network ProgrammingRapid Application Development-CS3011
-
8/6/2019 5417.Java TCP Programming
49/67
Accepting Socket
The main task of server socket is to receiveincoming connection requests and generate a
java.net.Socket object that encapsulates each
request.Incoming connections are queued until the
program retrieves them one at a time by
invoking the accept() method.The accept() method takes no arguments, andreturns the next connection in the queue.
3/23/2011 49Network ProgrammingRapid Application Development-CS3011
Example SimpleServer java
-
8/6/2019 5417.Java TCP Programming
50/67
Example -- SimpleServer.javaimport java.net.*;import java.io.*;
public class SimpleServer {public static void main(String args[]) {
ServerSocket server = null;port = 1234;
try {System.out.println(Attempting to bind a TCP port + port);server = new ServerSocket(port);
} catch(SecurityException se) {System.out.println(Trouble : + se.getMessage());
} catch(IOException ioe) {System.out.println(Trouble : + ioe.getMessage());
}3/23/2011 50Network ProgrammingRapid Application Development-CS3011
Example contd
-
8/6/2019 5417.Java TCP Programming
51/67
Example contd.try {
Socket socket = server.accept();
System.out.println(Accepting connection from: +socket.getInetAddress().getHostName());
socket.close();} catch(SecurityException se) {
System.out.println(Trouble : + se.getMessage());} catch(IOException ioe) {
System.out.println(Trouble : + ioe.getMessage());
}}
}
3/23/2011 51Network ProgrammingRapid Application Development-CS3011
-
8/6/2019 5417.Java TCP Programming
52/67
Getting ServerSocket Info
Server socket objects have two identifyingattributes: the port number and theInetAddress they are bound to.
The java.net.ServerSocket class providesmethods to query two values
The getInetAddress() method returns the IP
address of the interface to which the serversocket is bound.
The getLocalPort() returns the port the server
socket is bound to.3/23/2011 52Network ProgrammingRapid Application Development-CS3011
-
8/6/2019 5417.Java TCP Programming
53/67
Terminating ServerSocket
A server socket may be terminated simply byinvoking the no argument close () method.
Closing the server socket will not affectconnections that have already been returnedby an accept () invocation.
The signature is as follows void close () throws IO Exception;
3/23/2011 53Network ProgrammingRapid Application Development-CS3011
Example the server side of the Echo Client
-
8/6/2019 5417.Java TCP Programming
54/67
Example the server side of the Echo Client
import java.net.*;import java.io.*;public class EchoServer {
public static void main(String args[]) {Socket clientSocket;ServerSocket serverSocket;int port = 4444;try {
//Creating ServerSocket instanceserverSocket = new ServerSocket(port);
} catch(SecurityException se) {System.out.println (Trouble : + se.getMessage());
} catch(IOException ioe) {System.out.println (Trouble : + ioe.getMessage());
}3/23/2011 54Network ProgrammingRapid Application Development-CS3011
try {
-
8/6/2019 5417.Java TCP Programming
55/67
try { //Server is accepting connectionclientSocket = serverSocket.accept();
// Initializing I/O streamsPrintWriter out = new PrintWriter(clientSocket.getOutputStream(),true);BufferedReader in = new BufferedReader(new
InputStreamReader (clientSocket.getInputStream())); //Server is ready to start conversation
//Initiate conversation with ClientString inputLine;do {
inputLine = in .readLine();out .println (Received : + inputLine);
}while(!( inputLine.equalsIgnoreCase (quit)));
3/23/2011 55Network ProgrammingRapid Application Development-CS3011
//Close all IO streams and sockets
-
8/6/2019 5417.Java TCP Programming
56/67
//Close all IO streams and sockets
in.close();out.close();
clientSocket.close();serverSocket.close();
} catch(IOException ioe) {System.out.println (Trouble : + ioe.getMessage());}
}}
3/23/2011 56Network ProgrammingRapid Application Development-CS3011
-
8/6/2019 5417.Java TCP Programming
57/67
Chat Messenger
3/23/2011 Network ProgrammingRapid Application Development-CS3011 57
Lecture - 5
Application of Network Programming
-
8/6/2019 5417.Java TCP Programming
58/67
3/23/2011 Network ProgrammingRapid Application Development-CS3011 58
-
8/6/2019 5417.Java TCP Programming
59/67
Example illustrating ChatClient through Socket Programming
-
8/6/2019 5417.Java TCP Programming
60/67
import java.net.*;import java.io.*;public class ChatClient {
public static void main(String[] args){ Socket echoSocket = null;
PrintWriter out = null;
BufferedReader in = null;try {
echoSocket = new Socket("127.0.0.1",4444);out = new PrintWriter(echoSocket.getOutputStream(),true);
in = new BufferedReader( newInputStreamReader(echoSocket.getInputStream())) ;
}
3/23/2011 60Network Programming
Rapid Application Development-CS3011
Example illustrating ChatClient through Socket Programming
-
8/6/2019 5417.Java TCP Programming
61/67
} catch(UnknownHostException ue) {
System.out.ptintln (Trouble: + ue.getMessage());} catch(IOException ioe) {
System.out.ptintln (Trouble: + ioe.getMessage());}
BufferedReader stdIn = new BufferedReader(newInputStreamReader(System.in));
String userInput;
3/23/2011 61Network Programming
Rapid Application Development-CS3011
Example illustrating ChatClient through Socket Programming
-
8/6/2019 5417.Java TCP Programming
62/67
System.out.println("Received : " + in .readLine());do{
System.out.print("Send : ");userInput = stdIn .readLine();out .println(userInput);System.out.println("Received : " + in .readLine());
}while(! (userInput.equalsIgnoreCase("bye"));
out.close();in.close();stdIn.close();echoSocket.close();
}
} 3/23/2011 62Network Programming
Rapid Application Development-CS3011
-
8/6/2019 5417.Java TCP Programming
63/67
3/23/2011Network Programming
Rapid Application Development-CS3011 63
Chat Server
// Example illustrating ChatServer through Socket Programming
-
8/6/2019 5417.Java TCP Programming
64/67
3/23/2011Network Programming
Rapid Application Development-CS3011 64
import java.net.*;import java.io.*;public class ChatServer {
public static void main(String args[]){
Socket clientSocket;ServerSocket serverSocket = null;int port = 4444;
try{ //Creating ServerSocket instance
serverSocket = new ServerSocket(port);}catch(SecurityException se) {System.out.println("Trouble : " + se.getMessage());
}catch(IOException ioe) {
System.out.println("Trouble : " + ioe.getMessage()); }
// Example illustrating ChatServer through Socket Programming
-
8/6/2019 5417.Java TCP Programming
65/67
3/23/2011Network Programming
Rapid Application Development-CS3011 65
//Server is accepting connectionclientSocket = serverSocket.accept();
// Initializing I/O streamsPrintWriter out = new PrintWriter(clientSocket.getOutputStream());
BufferedReader in = new BufferedReader(newInputStreamReader(clientSocket.getInputStream()));
BufferedReader stdIn = new BufferedReader(newInputStreamReader(System.in));
//Server is ready to start conversation //Initiate conversation with Client
String inputLine, userInput;out .println("Server is listening on port " + port);
// Example illustrating ChatServer through Socket Programming
-
8/6/2019 5417.Java TCP Programming
66/67
3/23/2011Network Programming
Rapid Application Development-CS3011 66
do {inputLine = in .readLine();System.out.println("Received : " + inputLine);
System.out.print("Send : ");userInput = stdIn .readLine();out .println(userInput);
}while(!(userInput.equalsIgnoreCase("bye")));
//Close all IO streams and socketsin.close();
out.close();clientSocket.close();serverSocket.close();
}}
A ig t
-
8/6/2019 5417.Java TCP Programming
67/67
Assignment
Create a Chat Messenger with GUI using AWT and Event Handling.
top related