日期:2014-05-19  浏览次数:20807 次

请教一个java socket的问题,为何server端读不到client端发送过来的消息,有什么办法可以解决
server端:
public class IS {

ServerSocket server = null;
Socket client = null;

public static void main(String[] args) {
new IS().sendAndRecv();
}

public void sendAndRecv() {
try {
server = new ServerSocket(8003);
while (true) {
client = server.accept();
OutputStream os = client.getOutputStream();
InputStream is = client.getInputStream();
int size = is.available();
byte[] a = new byte[size];
is.read(a);
String strque = new String(a);
System.out.println(strque);
os.write("lisi he zhangsan ye!".getBytes());
os.flush();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
client端:
public class IC {
Socket client = null;

public static void main(String[] args) {
new IC().sendAndRecv();
}

public void sendAndRecv() {
try {
client = new Socket("127.0.0.1", 8003);
OutputStream os = client.getOutputStream();
InputStream is = client.getInputStream();
os.write("zhangsan he li si is firend".getBytes());
os.flush();
int size = is.available();
byte[] a = new byte[size];
is.read(a);
String strque = new String(a);
System.out.println(strque);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
socket问题 socket

------解决方案--------------------
客户端读的时候需要等待一段时间才会有值的,

public class Server {
ServerSocket server = null;
Socket client = null;

public static void main(String[] args) {
new Server().sendAndRecv();
}

public void sendAndRecv() {
try {
server = new ServerSocket(8003);
while (true) {
client = server.accept();
System.out.println(client.getInetAddress() + "已连接......");
OutputStream os = client.getOutputStream();
InputStream is = client.getInputStream();
int i = -1;
byte[] buf = new byte[1024];
i = is.read(buf);
System.out.println(new String(buf, 0, i));
System.out.println("信息已经读取完成.");
os.write("hello world!".getBytes());
os.flush();
os.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public class Client {
Socket c