| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121 |
- package server;
- import java.io.DataInputStream;
- import java.io.DataOutputStream;
- import java.io.IOException;
- import java.net.Socket;
- import server.match.Match;
- public class NetworkUser {
- private String name;
- private Socket client;
- private DataOutputStream dout;
- private DataInputStream din;
- private Thread receivethread;
- private Match match;
- private int pid;
- //A thread which handles the server communication to a client
- public NetworkUser(Socket client) {
- this.client = client;
- try {
- dout = new DataOutputStream(client.getOutputStream());
- din = new DataInputStream(client.getInputStream());
- } catch (IOException e) {
- match.stopMatch();
- }
- try {
- client.setSoTimeout(5000);
- name = din.readUTF();
- System.out.println(name);
- client.setSoTimeout(0);
- } catch (IOException e) {
- }
- receivethread = new Thread(new Runnable() {
- @Override
- public void run() {
- while (true) {
- receiveMessage();
- }
- }
- });
- }
- /* NETWORK CONTROL METHODS */
- public boolean checkConnection() {
- try {
- dout.writeUTF("0");
- } catch (IOException e) {
- return false;
- }
- return true;
- }
- public void startMatch(String p1, String p2, int pid, Match match) {
- sendMessage("1|" + p1 + "|" + p2);
- this.pid = pid;
- this.match = match;
- receivethread.start();
- }
- public void sendOverlayText(String text) {
- sendMessage("3|" + text + " ");
- }
- public void sendUpdateMessage(String m) {
- sendMessage("2|" + m);
- }
-
- public void sendChatMessage(String m) {
- sendMessage("4|" + m);
- }
- private void sendMessage(String m) {
- try {
- dout.writeUTF(m);
- } catch (IOException e) {
- System.err.println("User disconnected");
- match.stopMatch();
- }
- }
- public void receiveMessage() {
- try {
- String message = din.readUTF();
- String[] messagesplit = message.split("\\|");
- switch (messagesplit[0]) {
- case "1": // Player input information
- match.setPlayerDirection(pid, Integer.parseInt(messagesplit[1]));
- if (Integer.parseInt(messagesplit[2]) == 1) {
- match.playerShoot(pid);
- }
- break;
- case "2":
- match.sendChatMessage("[" + name + "] " + messagesplit[1]);
- break;
- }
- } catch (IOException e) {
- System.err.println("User disconnected");
- match.stopMatch();
- }
- }
-
- public void close() throws IOException{
- receivethread.stop();
- din.close();
- dout.close();
- client.close();
- }
- /* GETTERS AND SETTERS */
- /**
- * @return the name of the user
- */
- public String getName() {
- return name;
- }
- }
|