客户端代码:
packagecom.kaige123.net01;importjava.io.IOException;importjava.io.InputStream;importjava.io.OutputStream;importjava.net.Socket;importjava.net.UnknownHostException;/**
*凯哥
*/publicclassClient{publicstaticvoidmain(String[] args)throwsException{// 如果对方服务器不存在就会报错Socket socket =newSocket("127.0.0.1",8080); InputStream input = socket.getInputStream();OutputStream output = socket.getOutputStream();output.write("你好服务器,我是凯哥,你还记得我吗?".getBytes());output.flush();//赶紧把内容输出到对方byte[] b=newbyte[1024];intlen=input.read(b);System.out.println("服务器说:"+newString(b,0,len));output.close();input.close();socket.close();}}
packagecom.kaige123.net01;importjava.io.IOException;importjava.io.InputStream;importjava.io.OutputStream;importjava.net.ServerSocket;importjava.net.Socket;/**
*凯哥
*/publicclassServer{publicstaticvoidmain(String[] args)throwsException{// 如果都被占用 那就会抛异常// 建立好一个服务端 监听8080端口ServerSocket server =newServerSocket(8080);// 等待客户端来连接服务器Socket socket = server.accept();//代码运行到这句就会卡主 堵塞 等待InputStream input = socket.getInputStream();OutputStream output = socket.getOutputStream();byte[] b =newbyte[1024*5];intlen = input.read(b);String s =newString(b,0, len);System.out.println(s);s ="你好凯哥,我是从东莞回来的美女!!";output.write(s.getBytes());output.close();input.close();socket.close();}}