package network; import java.io.IOException; import java.io.PrintWriter; import java.io.Writer; import java.net.Socket; import java.util.Scanner; public class CliSocketTest { public void test(){ try { while(true){ Socket socket = new Socket("192.168.1.2",8888); Writer w = new PrintWriter(socket.getOutputStream()); Scanner scaner = new Scanner(System.in); w.write(scaner.nextLine()); System.out.println("輸入了書"); w.flush(); w.close(); } } catch (IOException e) { e.printStackTrace(); } } public static void main(String[] args) { new CliSocketTest().test(); } }
import java.io.*; import java.net.ServerSocket; import java.net.Socket; import java.util.Scanner; /** * Created by afeng on 2018/3/31. */ public class SersocketTest { /** * 创建服务器socket */ public static void serverSocket() throws IOException { ServerSocket serverSocket = null; try { serverSocket = new ServerSocket(8888); Socket socket = null; while(true){ socket = serverSocket.accept(); System.out.println("监听到哦了"); Scanner scanner = new Scanner(socket.getInputStream()); while(scanner.hasNextLine()){ String msg = scanner.nextLine(); System.out.println(socket.getInetAddress()+"說:"+msg); } } } catch (IOException e) { e.printStackTrace(); }finally { serverSocket.close(); } } public static void main(String[] args) { try { serverSocket(); } catch (IOException e) { e.printStackTrace(); } } }