import java.io.*; import java.net.*; import java.text.SimpleDateFormat; import java.util.Date;publicclassserver{//设置端口号/publicstaticint portNo=3333;publicstaticvoidmain(String[] args)throws IOException {//初始化serverSocket类ServerSocket s=newServerSocket(portNo);System.out.println("The Server is starting...");//建立socket连接(阻塞,直到有客户端连接)Socket socket=s.accept();//接收数据try{//构造输入流缓存BufferedReader bufReader=newBufferedReader(newInputStreamReader(socket.getInputStream()));PrintWriter out=newPrintWriter(newBufferedWriter(newOutputStreamWriter(socket.getOutputStream())),true);String time=newSimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(newDate());while(true){//按行读取输入内容String strLine=bufReader.readLine();//如果收到byebye则退出循环if(strLine.equals("byebye")){break;}System.out.println("In the Server reveived the info: "+strLine);//向客户端发送接收到的数据System.out.println("The server is send the received msg to the client...");out.println("The received msg is: "+strLine+" and The time is:"+time);}}catch(Exception e){e.printStackTrace();}finally{System.out.println("close the Server socket and the io");//关闭socket,断开连接socket.close();s.close();}}}
客户端
import java.io.*; import java.net.*;publicclassclient{/*** @param args*/publicstatic String clientName="laughcry";//设置端口号publicstaticint portNo=3333;publicstaticvoidmain(String[] args)throws IOException {// TODO Auto-generated method stub//设置连接地址类,连接本地,描述使用本socket的ip地址InetAddress addr=InetAddress.getByName("localhost");//初始化socket类Socket socket=newSocket(addr,portNo);try{System.out.println("socket="+socket);//设置io句柄BufferedReader bufReader=newBufferedReader(newInputStreamReader(socket.getInputStream()));PrintWriter out=newPrintWriter(newBufferedWriter(newOutputStreamWriter(socket.getOutputStream())),true);//向服务器端发送数据out.println("Hello server ,I am "+clientName);//接受服务器返回的信息String str=bufReader.readLine();System.out.println("The msg from server is: "+str);out.println("byebye");}catch(Exception e){e.printStackTrace();}finally{//关闭连接System.out.println("close the client socket and the io.");socket.close();}}}