Java通过套接字客户端,服务器,LAN发送自定义对象

时间:2016-05-28 20:23:35

标签: java sockets send custom-object

我想通过套接字从Client向Server发送对象(自定义类)。这是我的代码:

服务器

private class SocketServerThread extends Thread {

    @Override
    public void run() {
        try {
            serverSocket = new ServerSocket(socketServerPORT);

            while (true) {
                clientSocket = serverSocket.accept();
                ObjectInputStream inObject = new ObjectInputStream(
                        clientSocket.getInputStream());
                try {
                    Te xxx = (Te) inObject.readObject();

                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }


                //DataInputStream dataInputStream = new DataInputStream(
                        //clientSocket.getInputStream());
                //messageFromClient=dataInputStream.readUTF();

        activity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                //activity.msgFromC.setText(messageFromClient);
            }
        });
    }
}

客户端:

public Client(String aIPaddres, int aPort, Te u) {
    AddressIP = aIPaddres;
    Port = aPort;
    sendUser = u;
}
protected Void doInBackground(Void... arg0) {

    Socket clientSocket = null;

    try {

        clientSocket = new Socket(AddressIP, Port);
        ObjectOutputStream outObject = new ObjectOutputStream(
                clientSocket.getOutputStream());
        outObject.writeObject(sendUser);
        //DataOutputStream daneWyjsciowe = new DataOutputStream(
                //clientSocket.getOutputStream());
        //daneWyjsciowe.writeUTF("Czesc!" );

    } catch (UnknownHostException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        //response = "UnknownHostException: " + e.toString();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        //response = "IOException: " + e.toString();
    } finally {
        if (clientSocket != null) {
            try {
                clientSocket.close();

            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
    return null;

}

自定义类(Te.class):

public class Te implements Serializable {
public String message;
public Te(String m){
    message=m;
}

}

当我传递简单数据即String时没有问题。但现在我想传递对象,但服务器上总是有ClassNotFoundException。我读了很多堆栈,但我没有找到答案。你帮帮我吗?

0 个答案:

没有答案