服务器端为什么接收不到客户端发送过去的数据?
找了很久也没有找到是什么原因.
所以贴出来让大家帮忙解决,谢谢了.服务端:
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Vector;
public class Server extends java.lang.Thread{
ServerSocket ss = null;
ObjectInputStream ois = null;
public Server() {
try {
ss = new ServerSocket(1860);
System.out.println("服务器已启动...!");
} catch (IOException e) {
e.printStackTrace();
}
}
public void run() {
String type = null;
while (true) {
try {
Socket client = ss.accept();
ois = new ObjectInputStream(client.getInputStream());
try {
System.out.println(ois.readObject());
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void main(String args[]) {
new Server().start();
}
}
客户端:
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
public class Client{
public static void main(String[] args) {
try {
Socket s = new Socket("127.0.0.1",1860);
ObjectOutputStream oos = new ObjectOutputStream(s.getOutputStream());
UserInfo uinfo = new UserInfo();
uinfo.setName("lxh");
uinfo.setPassword("asdf");
oos.writeObject(uinfo);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Date;
public class UserInfo implements java.io.Serializable{
private String name = null;      
private String password = null;  
public UserInfo(){}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
private void writeObject(ObjectOutputStream oos){
try {
oos.writeUTF(name);
oos.writeUTF(password);
oos.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
private void readObject(ObjectInputStream ois) {
try {
name = ois.readUTF();
password = ois.readUTF();
} catch (IOException e) {
e.printStackTrace();
}
}
}

解决方案 »

  1.   

    uinfo.setPassword("asdf");
    oos.writeObject(uinfo);
    这里为什么没有
    oos.flush();
    ???????????
      

  2.   

    我运行你上面的代码,没问题,一切正常.
    结果是:UserInfo@8965fb
    你的UesrInfo类的writeObject,readObject方法是多余的,在这里没起作用.
      

  3.   

    奇怪.
    为什么在我这里就不行呢?
    如果把writeObject改为writeUTF可以接收到
    难道是JDK环境有问题?
    请问你的环境是怎么配制的?
    [email protected]