一个简单的聊天程序,请指点错在哪里了???
分2个程序,服务器和客户,为了方便输入,每个程序都专门建立了一个线程进行写,而主线程负责读编译没错,运行的效果却不对,请指点:
这个是服务器的:
程序代码:
import import import import import import public class ServerTest { public static void main(String[] args) { new ServerTest(PORT).gogo(); } private static final int PORT = 400; private ServerSocket server; private Socket socket; private PrintWriter writer; private BufferedReader reader; private BufferedReader in; //用户写 private Runnable writeThread; private String humanStr; private String clientStr; public ServerTest(int port){ try{ server = new ServerSocket(port); System.out.println("Server 已经建立..."); } catch(Exception e1){ e1.printStackTrace(); } } public void gogo(){ try{ System.out.println("in gogo()..."); socket = server.accept(); System.out.println("Client 已经连接..."); in = new BufferedReader(new InputStreamReader(System.in)); writer = new PrintWriter(socket.getOutputStream()); reader = new BufferedReader(new InputStreamReader(socket.getInputStream())); writeThread = new Runnable(){ public void run(){ try { while((humanStr = in.readLine()) != null){ System.out.println("Server: " + humanStr); writer.write(humanStr + "\n"); } } catch (IOException e2) { e2.printStackTrace(); } } }; new Thread(writeThread).start(); //System.out.println("before read"); while((clientStr = reader.readLine()) != null){ System.out.println("Client: " + clientStr + "\n"); } //System.out.println("after read"); in.close(); writer.close(); reader.close(); socket.close(); server.close(); } catch(Exception e3){ e3.printStackTrace(); } } }这个是客户端的:
程序代码:
import import import import import import public class ClientTest { public static void main(String[] args) { new ClientTest(PORT).gogo(); } private static final int PORT = 400; private Socket socket; private InetAddress address; private PrintWriter writer; private BufferedReader reader; private BufferedReader in; //用户写 private Runnable writeThread; private String humanStr; private String serverStr; public ClientTest(int port){ try{ address = InetAddress.getLocalHost(); socket = new Socket(address,port); } catch(Exception e1){ e1.printStackTrace(); } } public void gogo(){ try{ in = new BufferedReader(new InputStreamReader(System.in)); reader = new BufferedReader(new InputStreamReader(socket.getInputStream())); writer = new PrintWriter(socket.getOutputStream()); writeThread = new Runnable(){ public void run(){ try { while((humanStr = in.readLine()) != null){ System.out.println("Client: " + humanStr + "\n"); writer.write(humanStr + "\n"); } } catch (IOException e2) { e2.printStackTrace(); } } }; new Thread(writeThread).start(); //System.out.println("before read"); while ((serverStr = reader.readLine()) != null){ System.out.println("Server: " + serverStr + "\n"); } //System.out.println("after read"); in.close(); reader.close(); writer.close(); socket.close(); } catch(Exception e3){ e3.printStackTrace(); } } }求指教哇!!!谢谢。