Write a net program, include a server and client, client will send a string to the server, and server should print the string to the terminal, and return the length of string to the client, and finally the client should print the length sent from server. You should do it in TCP and UDP way.
Code:
TCP Client
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
import java.io.*; import java.net.Socket; publicclassTCPClient{ publicstaticvoidmain(String args[])throws Exception{ Socket socket = new Socket("127.0.0.1",65000); OutputStream os = socket.getOutputStream(); InputStream is = socket.getInputStream(); os.write(new String("xxx").getBytes()); int ch = 0; byte [] buff = newbyte[1024]; ch = is.read(buff); String content = new String(buff,0,ch); System.out.println(content); is.close(); os.close(); socket.close();
publicclassTCPServer{ publicstaticvoidmain(String args[])throws Exception{ //create and bind port ServerSocket ss = new ServerSocket(65000); //dead loop awaiting client sending request while(true){ Socket socket = ss.accept(); //only start after accept the require from client new LengthCalculator(socket).start();
publicvoidrun(){ try{ //output stream OutputStream os = socket.getOutputStream(); //input stream InputStream is = socket.getInputStream(); //ch for reading string length int ch=0; //buffer for input as isread only accpet byte so we have to made buff byte byte[] buff = newbyte[1024];
//isread will return the buff's length ch = is.read(buff);
String content = new String(buff,0,ch); System.out.println(content); //also os stream only accept array of bytes