socket的问题 为什么通过socket发送的数据有的时候客户端接收不到,有的时候接收得到

wuyuedetianpp 2012-07-31 12:30:34
服务端:

public class ServerDome {
public static void main(String[] args) {
ServerDome();
}

private static void ServerDome() {
ServerSocket ss;
Socket s;
BufferedReader in;
BufferedWriter out;

try {
ss=new ServerSocket(10000);
s=ss.accept();
in=new BufferedReader(new InputStreamReader(s.getInputStream()));
out = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
out.write("123");
out.close();
s.close();
ss.close();
} catch (IOException e) {
e.printStackTrace();
}
}


客户端:

public class ClientDome {
public static void main(String[] args) {
ClentDome();
}

private static void ClentDome() {
Socket s;
BufferedReader in;
BufferedWriter out;

try {
s=new Socket("127.0.0.1",10000);
in=new BufferedReader(new InputStreamReader(s.getInputStream()));
out = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
System.out.print("1");
if(in.ready()){
String str=in.readLine();
System.out.print("客户端:");
System.out.println(str);
}
in.close();
s.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
...全文
418 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
rain408806 2012-07-31
  • 打赏
  • 举报
回复
把 in.ready() 去掉就好了
  • 打赏
  • 举报
回复
不太了解
hou553403977 2012-07-31
  • 打赏
  • 举报
回复
[Quote=引用 2 楼 的回复:]

应该是你的那个in.ready()的问题
[/Quote]
简单点,
你运行下这个试试
public class ClientDome {
public static void main(String[] args) throws Exception {
Socket socket = new Socket("localhost", 10000);
BufferedReader in = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
if(in.ready())
{
String str = in.readLine();
System.out.print("客户端:");
System.out.println(str);
}
}
}
chenjkai1988 2012-07-31
  • 打赏
  • 举报
回复
也可能是,在服务器端没有调用out.flush()。数据可能还在服务器端缓存。
[Quote=引用 2 楼 的回复:]

应该是你的那个in.ready()的问题
[/Quote]
hou553403977 2012-07-31
  • 打赏
  • 举报
回复
应该是你的那个in.ready()的问题
a395885670 2012-07-31
  • 打赏
  • 举报
回复
网络不好丢包?
qunhao 2012-07-31
  • 打赏
  • 举报
回复
服务端发送的代码改为如下就可以了。

out.write("123\r\n"); //客户端读取的是一行数据,所以发送的数据后面需要加上换行符
out.flush(); //由于out是带缓冲的输出流,所以你需要调用这个方法把数据发送出去
System.in.read(); //不能发送数据后马上关闭socket,所以这里只是临时让你的程序不马上结束而已

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧