通过Java中的TCP套接字通信发送的对象的属性未更改

时间:2018-12-02 12:34:21

标签: java tcp socket.io objectinputstream objectoutputstream

我正在尝试使用Java的套接字通信功能来制作游戏。 我想一次通过对象发送消息,分数,玩家姓名和游戏输入。 在对象的属性中输入所需的数据后,我尝试通过该对象。但是,如果我通过set方法修改对象的属性,则传输的对象的属性不会更改。这是关键部分的问题吗?

这是我的代码。

有3个Java文件。 TestServer.java,TestClient.java,GameData.java


TestServer.java

import java.net.*;
import java.io.*;
import java.util.*;

public class TestServer {
HashMap clients;
private GameData gameData; // game data (score, name, input word, etc..)

TestServer() {
    clients = new HashMap();
    this.gameData = new GameData();
    Collections.synchronizedMap(clients);
}

public void start() {
    ServerSocket serverSocket = null;
    Socket socket = null;

    try {
        serverSocket = new ServerSocket(8080);  // server open
        System.out.println("server start");

        while (true) {  // Create and start a data I / O thread for the client after connecting to the client
            socket = serverSocket.accept();  // listening connect.
            System.out.println("[" + socket.getInetAddress() + ":" + socket.getPort() + "]" + "from connected.");
            ServerReceiver thread = new ServerReceiver(socket);  // A thread that receives and sends input from a client.
            thread.start();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
} // start()

void sendToALL(GameData msg) {
    Iterator it = clients.keySet().iterator();

    while (it.hasNext()) {
        try {
            ObjectOutputStream out = (ObjectOutputStream) clients.get(it.next());
            out.writeObject(msg);
        } catch (IOException e) {}
    } // while
} // sendToAll

public static void main(String[] args) {
    new TestServer().start();
} // Create Server Object and run server.

class ServerReceiver extends Thread {
    Socket socket;
    ObjectInputStream in;
    ObjectOutputStream out;

    ServerReceiver(Socket socket) {
        this.socket = socket; // client socket
        try {
            in = new ObjectInputStream(socket.getInputStream());
            out = new ObjectOutputStream(socket.getOutputStream());
        } catch (IOException e) {}
    }

    public void run() {
        String name = "";

        try {
            gameData = (GameData)in.readObject();
            name = gameData.getName();
            gameData.setMsg("#"+name+" has arrived.");
            System.out.println(gameData.getMsg());

            clients.put(name, out);
            System.out.println("The number of current server users is "+clients.size());

            while (in!=null) {
                gameData = (GameData)in.readObject();
                System.out.println(gameData.getMsg());
                sendToALL(gameData);
            }
        } catch (IOException e) {
            // ignore
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            gameData.setMsg("#"+name+" has left");
            sendToALL(gameData);
            clients.remove(name);
            System.out.println("["+socket.getInetAddress()+":"+socket.getPort()+"]"+"has disconnected");
            System.out.println("The number of current server users is "+clients.size());
        } // try
    } // run
} // ReceiverThread
} // class

TestClient.java

import java.net.*;
import java.io.*;
import java.util.Scanner;

public class TestClient {
GameData gameData;

public TestClient(String name) {
    try {
        String serverIp = ip_address;
        Socket socket = new Socket(serverIp, 8080);

        gameData = new GameData();
        System.out.println("connected to server");
        Thread sender = new Thread(new ClientSender(socket, name)); // This pass the user name to the server.
        Thread receiver = new Thread(new ClientReceiver(socket));

        sender.start();
        receiver.start();
    } catch (ConnectException ce) {
        ce.printStackTrace();
    } catch (Exception e) {}
}

public static void main(String[] args) {
    if(args.length != 1) {
        System.out.println("USAGE: java TestClient playerName");
        System.exit(0);
    }
    new TestClient(args[0]);
} // main

class ClientSender extends Thread {
    Socket socket;
    ObjectOutputStream out;
    String name;

    ClientSender(Socket socket, String name) {
        this.socket = socket; // server socket
        try {
            out = new ObjectOutputStream(socket.getOutputStream());
            this.name = name;
        } catch (Exception e) {}
    }

    public void run() {
        Scanner scanner = new Scanner(System.in);

        try {
            if(out!=null) {       // This send player name at first
                gameData.setName(name);
                out.writeObject(gameData);
            }

            while (out!=null) {
                System.out.println(gameData.setMsg("["+name+"]"+scanner.nextLine()));
                System.out.println("before writeObject : "+gameData.getMsg());
                out.writeObject(gameData);
            }
        } catch (IOException e) {}
    } // run
} // ClientSender

class ClientReceiver extends Thread {
    Socket socket;
    ObjectInputStream in;

    ClientReceiver(Socket socket) {
        this.socket = socket;
        try {
            in = new ObjectInputStream(socket.getInputStream());
        } catch (IOException e) {}
    }

    public void run() {
        while (in!=null) {
            try {
                gameData = (GameData)in.readObject();
                System.out.println(gameData.getMsg());
            } catch (Exception e) {}
        }
    } // run
} // ClientReceiver
} // class

GameData

import java.io.Serializable;

public class GameData implements Serializable {

private String inputWord;
private int score;
private String name;
private String msg;

public GameData() {
    this.score = 0;
    inputWord = "";
    name = "";
    msg = "";
}

public void setInputWord(String inputWord) {
    this.inputWord = inputWord;
}

public String getInputWord() {
    return this.inputWord;
}

public void setScore(int score) {
    this.score = score;
}

public int getScore() {
    return this.score;
}

public String setMsg(String msg) {
    this.msg = msg;
    return this.msg;
}

public String getMsg() {
    return msg;
}

public void setName(String name) {
    this.name = name;
}

public String getName() {
    return name;
}
}

0 个答案:

没有答案