Свойства объектов, отправляемых через сокет TCP в Java, не изменяются - PullRequest
0 голосов
/ 02 декабря 2018

Я пытаюсь сделать игру, используя возможности сокетов 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;
}
}
...