简单的一个Socket通信的例子,客户端从终端读取数据,发送给服务器。服务器接收数据后写到终端去。
搞不懂为什么客户端从终端读取数据后,总是flush不出去,必须等到close才发出去。要么就是我必须写满8k左右,才发送过去。
服务器端:
public class Server extends Thread {
public static void main(String[] args) {
new Server().start();
}
int port = 1343;
public void run() {
try{
ServerSocket server = new ServerSocket(port);
while(true){
try{
Socket readin = server.accept();
InputStream in = readin.getInputStream();
BufferedInputStream bin = new BufferedInputStream(in);
PrintWriter out = new PrintWriter(System.out);
int c;
while( (c = in.read()) != -1) out.write(c);
out.write("\r\n");
in.close();
bin.close();
out.close();
}catch(IOException e) {
System.err.println(e.getMessage());
System.exit(0);
} finally{
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
客户端:
public class Client extends Thread{
public static void main(String[] args) {
new Client().start();
}
int port = 1343;
public void run() {
try{
Socket client = new Socket();
client.setTcpNoDelay(true);
client.connect(new InetSocketAddress("localhost",port));
OutputStream out = client.getOutputStream();
BufferedWriter buf = new BufferedWriter(new OutputStreamWriter(out));
BufferedReader readin = new BufferedReader(new InputStreamReader(System.in));
String input;
while(true) {
input = readin.readLine();
if(!input.equals("exit")){
buf.write(input);
buf.flush();
}
else break;
}
buf.close();
readin.close();
client.close();
}catch(IOException e) {
e.printStackTrace();
}
}
}
------解决方案--------------------
再write一个 \r\n试试
------解决方案--------------------
flush应该是把数据写出去了的,不信你把Server程序里面的while改成if,是能够输出字符的,只是因为没有收到流结束的标识,所以就阻塞在Server这里。