一.Screenshots for each step
1.Client-Server message passing
(1)Client send hello to Server
(2)Server accept message from Client
(3)Server send hello to Client
(4)Client accept message from Server
二.Program
1.Client-Server message passing
(1)MyClient.java
import java.net.*;
import java.io.*;
class MyClient{ public static void main(String args[])throws Exception{
//establish socket connection to server
Socket s=new Socket("localhost",3333);
//create DateInputStream object din
DataInputStream din=new DataInputStream(s.getInputStream());
//create DataOutputStream object dout
DataOutputStream dout=new DataOutputStream(s.getOutputStream());
//create BufferedReader object br
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
//Defining string types str str2
String str="",str2="";
while(!str.equals("stop")){
// str readline
str=br.readLine();
//str write
dout.writeUTF(str);
//The batch output
dout.flush();
//read str2
str2=din.readUTF();
System.out.println("Server says: "+str2); }
//close resources
dout.close();
s.close();
}}
(2)MyServer.java
import java.net.*;
import java.io.*;
class MyServer{ public static void main(String args[])throws Exception{
//Create ServerSocket object ss and port is 3333
ServerSocket ss=new ServerSocket(3333);
//creating s and waiting for client connection
Socket s=ss.accept();
//create DateInputStream object din
DataInputStream din=new DataInputStream(s.getInputStream());
//create DataOutputStream object dout
DataOutputStream dout=new DataOutputStream(s.getOutputStream());
//create BufferedReader object br
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
//Defining string types str str2
String str="",str2="";
while(!str.equals("stop")){
// read str
str=din.readUTF();
System.out.println("client says: "+str);
//create readline str2
str2=br.readLine();
// write str2
dout.writeUTF(str2);
//The batch output
dout.flush();}
//close resources
din.close();
s.close();
ss.close();
}}