java网络编程入门程序问题?

import java.io.*;
import java.net.*;

public class ChatServer {
        public static void main(String []args) {
                try {
                        ServerSocket ss = new ServerSocket(6888);
                        Socket so = ss.accept();
                        BufferedReader br = new BufferedReader(new InputStreamReader(so.getInputStream()));
                        BufferedReader brs = new BufferedReader(new InputStreamReader(System.in));
                        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(so.getOutputStream()));
                        String s = br.readLine();
                        System.out.println("Client" + s);
                      String c = null;
                        while(s != "exit") {
                                System.out.println("Client : " + s);    
                                c = brs.readLine();
                                bw.write(c);
                                bw.flush();
                                System.out.println("Server : " + c);
                                s = br.readLine();    
                        }  
                        System.out.println("Chat Over");
                        br.close();
                        brs.close();
                        bw.close();
                }
                catch(Exception e) {}   
        }   
}

我的一个小程序,上面是server

import java.io.*;
import java.net.*;

public class ChatClient {
        public static void main(String []args) {
                try {
                        Socket so = new Socket("127.0.0.1",6888);
                        BufferedReader br = new BufferedReader(new InputStreamReader(so.getInputStream()));
                        BufferedReader brw = new BufferedReader(new InputStreamReader(System.in));
                        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(so.getOutputStream()));
                        String c = brw.readLine();
                        bw.write(c);
                        System.out.println("client" + c);
                        while(c != "exit") {
                                bw.write(c);
                                bw.flush();
                                System.out.println("Client : " + c);
                                System.out.println("Server : " + br.readLine());    
                                c = brw.readLine();
                        }   
                        System.out.println("Chat Over");
                        br.close();
                        brw.close();
                        bw.close();
                }
                catch(Exception e) {}   
        }   
}

这是client,其实就是一个简单的,白痴的对话器,但是我怎么调试也不对,编译通过了,但是运行的时候一直卡在那里,感觉是io出问题了,大师们劳烦看看呗。非常感谢,实在是自己看不出来了。。。。。

阅读 4.2k
1 个回答

不是一定要用Print,你原来那么写也是可以的,只不过你传输的数据中得有回车符("\r\n")
你原来写的bw.write(c)是没有换行符的,所以改成bw.write(c+"\r\n"),服务端readLine()就能读到,readLine是按行读取的,没有"\r\n"的话就识别不了,读不出来数据;所以客户端其实是发送出去数据了,只不过服务端没有读出来

推荐问题
logo
101 新手上路
子站问答
访问
宣传栏