Socket客户端不能接收到服务器数据呢?
服务器端程序:
import
java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class ServerSystem {
ServerSocket server;
Socket s;
ObjectInputStream ois;
ObjectOutputStream oos;
private void service() {
try {
server = new ServerSocket(6666);
while(true){
s = server.accept();
ois= new ObjectInputStream(s.getInputStream());
oos = new ObjectOutputStream(s.getOutputStream());
Student student = (Student)ois.readObject();
oos.writeInt(123);
System.out.println(student);
}
} catch (
IOException e) {
e.printStackTrace();
} catch (
ClassNotFoundException e) {
e.printStackTrace();
} finally{
try {
if (s != null){
s.close();
}
if (ois != null){
ois.close();
ois = null;
}
if (oos != null){
oos.close();
oos = null;
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
new ServerSystem().service();
}
}
客户端程序:
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.
UnknownHostException;
public class ManagerClient {
Socket s;
ObjectOutputStream oos;
ObjectInputStream ois;
public void start() {
try {
s = new Socket("127.0.0.1", 6666);
oos = new ObjectOutputStream(s.getOutputStream());
ois = new ObjectInputStream(s.getInputStream());
Student student = new Student("林浩",123456);
oos.writeObject(student);
int dataFromServer = ois.readInt();
System.out.println(dataFromServer);
} catch (UnknownHostException e) {
System.out.println("服务器未启动");
} catch (IOException e) {
e.printStackTrace();
} finally{
try {
if (s != null){
s.close();
}
if(oos != null){
oos.close();
oos = null;
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
new ManagerClient().start();
}
}
学生类:
import java.io.Serializable;
public class Student implements Serializable{
private String name;
private int password;
public Student(){
}
public Student(String name, int password){
this.name = name;
this.password = password;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getPassword() {
return password;
}
public void setPassword(int password) {
this.password = password;
}
@Override
public String toString() {
return "name:" + name + "password:" + password;
}
}
运行了, 服务器端可以接收到客户端发送的学生信息,并打印正确, 但是客户端却不能收到服务器发送的数据,并一直等待在readInt那儿 , 有些疑惑。
------解决方案--------------------out.flush();
把流清空,确保发送到客户端
如果不行再out.writeObjct( "\n")
\n确保流中的数据被发送
试试吧
------解决方案--------------------Java code
private void service() {
try {
server = new ServerSocket(6666);
while(true){
s = server.accept();
ois= new ObjectInputStream(s.getInputStream());
oos = new ObjectOutputStream(s.getOutputStream());
Student student = (Student)ois.readObject();
oos.writeInt(123);
oos.flush(); //刷新
System.out.println(student);
}
........