4
回答
请教一个简单的javaTCP通信的问题,感激
百度AI开发者大赛带你边学边开发,赢100万奖金,加群:418589053   
//Server
import java.net.*;
import java.io.*;
public class TalkServer2{
	public static void main(String[] args){
		BufferedReader cout = null; //接收客户端
		BufferedReader sin = null;
		BufferedWriter sout = null; //写入客户端流
		String sstr = null;
		String temp = null;
		boolean flag = false;
		try{
			ServerSocket server = new ServerSocket(9995);
			Socket client = server.accept();
			System.out.println("连接已建立!");
			while(true){
				cout = new BufferedReader(new InputStreamReader(client.getInputStream()));
				System.out.println("Client: " +cout.readLine());
				
				sout = new BufferedWriter(new OutputStreamWriter(client.getOutputStream()));
				sin = new BufferedReader(new InputStreamReader(System.in));
				while((temp=sin.readLine())!=null){
					sout.write(temp,0,temp.length());
					sout.newLine();
					sout.flush();
				}
				cout.close();
				sin.close();
				sout.close();
				client.close();
				server.close();
			}
		}  catch(Exception e){
			e.printStackTrace();
	    	}
	}
}



//Client

import java.net.*;
import java.io.*;
public class TalkClient2{
	public static void main(String[] args){
		BufferedReader cin = null;
		BufferedWriter cout = null; //写入服务端流;
		BufferedReader sout = null; //接收服务端流
		String cstr = null;
		String temp = null;
		try{
			    InetAddress ia = InetAddress.getLocalHost();
			    Socket socket = new Socket(ia,9995);
				
		while(true){
				
				cout = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
				cin = new BufferedReader(new InputStreamReader((System.in)));
				while((temp=cin.readLine())!=null){
					cout.write(temp,0,temp.length());
					cout.newLine();
					cout.flush();
				}
				
				sout = new BufferedReader(new InputStreamReader(socket.getInputStream()));
			    System.out.println("Server: " +sout.readLine());
				
			cout.close();
			cin.close();
			cout.close();
			sout.close();
			socket.close();
			
		}		
		    } catch(Exception e){
				e.printStackTrace();
			}
	}
}

客户端→ 服务端 的时候可以发送

服务端→ 客户端发送后客户端无显示,先关服务端,再关客户端后有显示(用的写字板和cmd)

这是为什么呢?为什么不能直接服务端到客户端发送,立即在客户端显示呢?


举报
it_junior
发帖于2年前 4回/214阅

以下是问题补充:

  • @it_junior :其实我想说,得手动关闭客户端,服务端的通信才会在客户端显示,可能表达的不准确吧,见谅 (2年前)
顶部