最近学习研究socket编程,问题是服务器和客户端能够互相通信发送消息,发现当服务器端- socket = server.accept();
复制代码 完成连接后,使用PrintWriter- out=new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())),true);
复制代码 获取输出流,则客户端能够接收到,而用BufferedWriter却不行。不知道为什么。客户端都是使用- BufferedReader in = new BufferedReader( new InputStreamReader(socket.getInputStream()));
复制代码 接受输入流。
附上代码
服务器端核心代码:
- while (booleans) {
- server = new ServerSocket(8998);
- test.append("服务器套接字已经创建成功\n");
- while (true) {
- test.append("等待客户机连接\n");
- socket = server.accept();
- read = new InputStreamReader(socket.getInputStream());
- out=new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())),true);
- while (true) {
- char byt[] = new char[1024];
- int len = read.read(byt);
- String s = new String(byt, 0, len);
- Date date = new java.util.Date();
- String time = String.format("%tr", date);
- test.append("客户机: " + time + "\n " + s);
- out.println(convertStr(s));
- }
- }
- }
复制代码
客户端核心代码
- socket=new Socket("127.0.0.1",8998);
- writer=new PrintWriter(socket.getOutputStream(),true);
- test.append("完成连接\n");
- System.out.println("输入流");
- final BufferedReader in = new BufferedReader( new InputStreamReader(socket.getInputStream()));
- Thread thread=new Thread(new Runnable() {
- @Override
- public void run() {
- // TODO Auto-generated method stub
- try {
- while(true){
- System.out.println("ok");
- String line = null ;
- while((line=in.readLine())!=null&&!line.equals("")){
- test.append("服务器返回数据:"+line+"\n");
- }
- }
- } catch (IOException e1) {
- // TODO Auto-generated catch block
- e1.printStackTrace();
- }
- }
- });
- thread.start();
复制代码
求大神指点! |