ServerDemo
import java.io.* ; import java.net.* ; public class serverDemo { public static void main(String [] args){ ServerSocket serverSocket = null ; Socket socket = null ; String line ; try{ serverSocket = new ServerSocket (5555) ; socket = serverSocket.accept(); System.out.println("Success") ; System.out.println(); BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())) ; BufferedReader sin = new BufferedReader (new InputStreamReader(System.in)); PrintWriter os = new PrintWriter(socket.getOutputStream()); System.out.println("From Client: " + in.readLine()) ; line = sin.readLine(); while(!line.equals("bye")) { os.println(line) ; os.flush() ; System.out.println("From Client:" + in.readLine()) ; line = sin.readLine(); } in.close() ; sin.close() ; os.close() ; socket.close(); serverSocket.close(); } catch (Exception e) { e.printStackTrace() ; } } }
ClientDemo。
import java.net.* ; import java.io.*; public class ClientDemo { public static void main(String [] args){ try{ Socket socket = new Socket("192.168.1.116",5555) ; BufferedReader sin = new BufferedReader(new InputStreamReader(System.in)) ; BufferedReader in = new BufferedReader (new InputStreamReader(socket.getInputStream())) ; PrintWriter os = new PrintWriter(socket.getOutputStream()) ; String line ; line = sin.readLine() ; while(!line.equals("bye")){ os.println(line) ; os.flush() ; System.out.println("Client:" + line); System.out.println("From Server:" + in.readLine()) ; line = sin.readLine() ; } os.close(); sin.close() ; in.close(); socket.close() ; }catch (Exception e) { e.printStackTrace() ; } } }