日期:2014-05-20 浏览次数:20770 次
import java.io.*; import java.net.*; public class Server extends ServerSocket { private static final int SERVER_PORT = 10000; public Server() throws IOException { super(SERVER_PORT); try { while (true) { Socket socket = accept(); new CreateServerThread(socket); } } catch (IOException e) { } finally { close(); } } // --- CreateServerThread class CreateServerThread extends Thread { private Socket client; private BufferedReader in; private PrintWriter out; public CreateServerThread(Socket s) throws IOException { client = s; in = new BufferedReader(new InputStreamReader(client.getInputStream(), "GB2312")); out = new PrintWriter(client.getOutputStream(), true); out.println("--- Welcome ---"); start(); } public void run() { try { String line = in.readLine(); while (!line.equals("bye")) { String msg = createMessage(line); out.println(msg); line = in.readLine(); } out.println("--- See you, bye! ---"); out.close(); in.close(); client.close(); } catch (IOException e) { } } private String createMessage(String line) { return "your input is:"+line; } } public static void main(String[] args) throws IOException { new Server(); } }
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.Socket; import java.net.UnknownHostException; public class Client { private static Socket client; private static final int SERVER_PORT = 10000; private static BufferedReader in; private static PrintWriter out; private static String mesFormSer; public Client() throws Exception { client = new Socket("192.168.1.103", SERVER_PORT);//这里ip要看情况改 BufferedReader sin = new BufferedReader(new InputStreamReader(System.in)); in = new BufferedReader(new InputStreamReader(client.getInputStream())); out = new PrintWriter(client.getOutputStream(),true); System.out.println(in.readLine()); String message = sin.readLine(); while (!message.equals("Quit")) { out.println(message); this.mesFormSer = in.readLine(); System.out.println(this.mesFormSer); message = sin.readLine(); } in.close(); out.close(); sin.close(); client.close(); } public static void main(String args[]) { try { new Client(); } catch (Exception e) { e.printStackTrace(); } } }