最好在DOS界面演示,由于在Eclipse输入法问题,只能聊一两句 客户端: import java.io.InputStream; import java.io.OutputStream; import java.net.Socket; import java.util.Scanner; /* * 客户端接收控制台的数据,发送到服务端, * 当服务端接收到数据后,回客户端一条信息。 */ public class SendClient { public static void main(String[] args) throws Exception { //发送端,发送的ip和端口 Socket socket=new Socket("127.0.0.1", 8888); OutputStream os=socket.getOutputStream();//发送给服务器 InputStream is=null;//读取收服务器发送来的数据 byte[]b=new byte[1024];//接收缓存 System.out.println("请输入发送数据"); Scanner sc=new Scanner(System.in); String str=null; while(true){ str=sc.nextLine(); if("000".equals(str)){//输入000结束 break; } byte[]a=str.getBytes(); //若是接收是用缓冲流的话,有readLine()时,发送端必定要有回车换行符服务器才能接受到 os.write(a, 0, a.length); os.write("\r\n".getBytes()); //读取服务器发送来的数据 is=socket.getInputStream();//得到读取管道。 int len=is.read(b); System.out.println(new String (b,0,len));//打印出来 } socket.close(); os.close(); } } 服务端: import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.ServerSocket; import java.net.Socket; import java.security.Provider.Service; import java.util.Scanner; /* * 客户端接收控制台的数据,发送到服务端, * 当服务端接收到数据后,回客户端一条信息。 */ public class ReceivceClient { public static void main(String[] args) throws Exception { //建立接收 ServerSocket serverSocket=new ServerSocket(8888); //返回的是一个socket Socket socket=serverSocket.accept();//监听,看有没有客户端链接,此方法有阻塞,接收不到不会往下执行 //得到读取管道 InputStream is=socket.getInputStream(); //建立发送管道 OutputStream os=null; Scanner sc=new Scanner(System.in); byte[]a=new byte[1024];//数据缓冲区 int len=-1; String string; while((len=is.read(a))!=-1){ //接收打印 String str=new String(a, 0,len); System.out.println(str); //发送 os=socket.getOutputStream(); string=sc.nextLine(); if("000".equals(string)){ break; } //若是接收是用缓冲流的话,有readLine()时,发送端必定要有回车换行符服务器才能接受到 os.write(string.getBytes()); os.write("\r\n".getBytes()); } serverSocket.close(); os.close(); } }