Write a client server program in Java using sockets

advertisement
CS2505 – JavaLabSheet01
February, 2011
Write a client server program in Java using sockets. The client sends the sentence “Hi
there” to the server and then reads in a line with the answer from the server. The client
prints the answer on the screen. The server reads the sentence from the clients
and sends back to them the answer “Welcome from the server”. The server prints on
the screen the sentence received from the client.
Steps:
client
socket.
creates a BufferedReader object attached to the input stream of the client
socket.
oses the socket.
nd creates a
Socket object for each connection.
server socket.
server
socket.
ads the sentence from the input stream.
Solution:
Java client (TCP)
// The import directive tells the compiler where to look for the class
// definitions and we import all the classes from java.io and java.net
import java.io.*;
import java.net.*;
public class TCPClient {
public static void main(String argv[]) throws Exception {
// In TCP/IP protocol each computer has an IP address
// In TCP/IP different services on same machine have different ports
// The port number & IP address define the TCP/IP connection
// localhost is a special address used to designate the loopback address
// localhost has the IP address 127.0.0.1
// Create the client socket with the address: localhost, port 6789
// Prepare an object for writing in the output stream
// Prepare an object for reading from the input stream
// Write the data on the output stream
// Read the data from the input stream
// Print the data on the screen
// Close the socket
}
}
Java server (TCP)
// The import directive tells the compiler where to look for the class
// definitions and we import all the classes from java.io and java.net
import java.io.*;
import java.net.*;
public class TCPServer {
public static void main(String argv[]) throws Exception {
// The server’s IP address is the computer’s IP address
// Create a server socket object that listens at port 6789
// Make an infinite loop
// Accept a connection from the clients and create a new socket
// Prepare an object for reading from the input stream
// Prepare an object for writing in the output stream
// Read the data from the input stream
// Print the data on the screen
// Write the data on the output stream
}
}
Write down the implementation of the proposed solution. Compile the java programs
and run first the server and then the client. Notice that the server process
doesn’t finish its execution. The only way to close the server is to destroy its
process. After compiling and running the example, discuss the implementation:
Download
Random flashcards
Arab people

15 Cards

Radiobiology

39 Cards

Radioactivity

30 Cards

Nomads

17 Cards

Create flashcards