Java网络编程,客户端和服务端相互发送信息,可是我写的双方都没读到对方发送的信息,代码如下

2024-12-04 10:26:48
推荐回答(3个)
回答1:

这个地方有问题,第一,你必须写入newLine,要不会造成阻塞;第二,你必须先flush后才能读服务器;第三,你从控制台输入应该有个结束标志,要不你在while里面把bw关闭了,你还怎么循环

客户端这个地方重写一下,

		while(true)	{
temp=br.readLine();
if(temp.equals("over")){
break;
}
bw.write(temp);
bw.newLine();//如果没有,使用readLine则会造成莫名等待
bw.flush();
}

 不一定改全了,你先试试这些改动,如有问题再找

回答2:

把 System.out.println(reader.readLine()); 这句去掉

把 bw.close(); 去掉

下面是你的代码,运行试试

客户端

package com.pzr.demo20161021;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;

public class demo3 {
    public static void main(String args[]){
        try {
            Socket socket  = new Socket("127.0.0.1",8888);
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
            
            
            while(true){
                System.out.println("请输入消息:");
//                System.out.println("服务器发过来的消息:"+reader.readLine());
                bw.write(br.readLine());
                bw.newLine();  
                bw.flush();
            }
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

 服务端

package com.pzr.demo20161021;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class demo4 {
    public static void main(String args[]){
        try {
            ServerSocket serverSocket =new ServerSocket(8888);
            Socket socket = serverSocket.accept();
            System.out.println(socket.getInetAddress().getHostAddress()+"已连接");
            BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            BufferedWriter witer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
            String string = null;
            while((string = reader.readLine()) != null){
                System.out.println(string);
            }
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            while((string = br.readLine()) != null){
                witer.write(string);
                witer.newLine();
                witer.flush();
            }
            reader.close();
            br.close();
            
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

回答3:

tcp的东西忘记了,感觉应该是端口的问题。