Вы находитесь на странице: 1из 2

TCP(Java)

Create a socket and bind to port ServerSocket a=new ServerSocket(9876)


Wait for client to connect Socket b=a.accept();
Type following programs in two files named server.java and client.java . Compile the programs. Now open two windows. In one window give command java server. In another window give command java client. The server has sent a string ramprasad.
import java.net.*; import java.io.*; class server { public static void main(String args[]) throws IOException { ServerSocket a=new ServerSocket(9876); System.out.println("address binding over"); Socket b=a.accept(); System.out.println("got client"); DataOutputStream d=new DataOutputStream(b.getOutputStream()); d.writeUTF("ramprasad"); a.close(); } }

class client { public static void main(String args[]) throws IOException { Socket p=new Socket(InetAddress.getLocalHost(),9876); System.out.println(p+" connected"); DataInputStream q=new DataInputStream(p.getInputStream()); String r=new String(q.readUTF()); System.out.println("received "+r); p.close(); } }

EXCERCISE 1. Modify the above program so that the server sends two strings. 2. Modify the given program so that the client sends the string. 3. Modify the given program so that client sends a string kapil to the server. The server sends a string gopal to the client.

4. Write program so that client sends a string to the server. The server deletes the first letter and sends back the string to the server. [Notation: g.substring(2) will delete the first two letters of string g. Let g=kapil h=g.substring(2) will make h=pil] 5. The server sends two strings to the client. The client joins them and sends it to the server. [g+h joins strings g and h. Let g=ram h=ok p=g+h will make p=ramok] 6. Modify the server of the given example program (the client remains unchanged). The server gets connected to two clients. To first client the server sends ram. To second client the server sends hari. Open three windows: In one window execute the server. In another two windows execute the client. [Hint: use accept system call twice] 7. Make three classes: server, clienta and clientb. The clienta sends a string ram to the server. The clientb sends string hari to server. 8. In the context of above question: The server sends back the strings to opposite clients. 9. Make three classes: client, servera, serverb. Let ports of servers are 9876 and 9877. The client gets connected to both servers. To servera the client sends string ram. To serverb the client sends string hari. 10. In the context of above question: both servers send a string to the client. The Client joins them and prints. Let servers send ram and ok the client will output ramok. 11. In the context of above question: The client sends back the strings to opposite servers.

Вам также может понравиться