package rom; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.ServerSocket; import java.net.Socket; public class Demo2 { private ServerSocket serverSocket; private Socket socket; /* * 服务端:接收客户端信息 */ public static void main(String[] args) throws IOException { new Demo2().run(); } public void run() throws IOException { serverSocket = new ServerSocket(8998); System.out.println("等待客户机连接"); socket = serverSocket.accept(); //如果没有客户端连接,accept这条代码会堵塞一直等待设备连接 System.out.println("连接成功"); BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream())); //获取socket里面携带的流 while (true) { //只需要连接一次设备和设置一次接收流,所以上面的内容不需要在循环里 String string = reader.readLine(); //获取流里面的一行信息 System.out.println("客户端信息:"+string); try { Thread.sleep(2000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("信息接收完毕"); //reader.close(); //关闭流 ,因为我们需要一直接收信息,所以流不能关闭 } } }
package rom; import java.io.IOException; import java.io.PrintWriter; import java.net.ServerSocket; import java.net.Socket; import java.net.UnknownHostException; import java.util.Scanner; /* * 客户端:向服务端发送信息 */ public class Demo1 { private PrintWriter writer; private Socket socket; public static void main(String[] args) throws IOException { new Demo1().run(); } public void run() throws IOException { System.out.println("尝试连接"); socket = new Socket("192.168.0.210", 8998); //连接客户端、IP和端口 System.out.println("连接成功"); writer = new PrintWriter(socket.getOutputStream(),true); //将流发送给客户端 while (true) { //只需要连接一次设备,所以上面的内容不需要在循环里 System.out.println("请输入发送内容:"); Scanner scanner = new Scanner(System.in); //控制台输入发送内容 writer.println(scanner.nextLine()); //给流添加内容 System.out.println("信息发送成功"); try { Thread.sleep(2000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } //writer.close(); //关闭流 ,因为我们需要一直发送信息,所以流不能关闭 } } }
结果:
备注:服务端的程序需要先运行。