This site requires JavaScript, please enable it in your browser!
Greenfoot back
fejfo
fejfo wrote ...

2015/8/22

Trouble with Sockets and multiplayer (Multithreadded Server)

1
2
fejfo fejfo

2015/8/22

#
My problem is it doesn't work I'll tell you what I've done and what I've tried ( I get this exception :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
java.net.ConnectException: Connection refused: connect
    at java.net.DualStackPlainSocketImpl.connect0(Native Method)
    at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:79)
    at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
    at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
    at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
    at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
    at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
    at java.net.Socket.connect(Socket.java:589)
    at java.net.Socket.connect(Socket.java:538)
    at java.net.Socket.<init>(Socket.java:434)
    at java.net.Socket.<init>(Socket.java:211)
    at fejfo.Client.<init>(Client.java:38)
    at Strater.act(Strater.java:66)
    at greenfoot.core.Simulation.actWorld(Simulation.java:600)
    at greenfoot.core.Simulation.runOneLoop(Simulation.java:535)
    at greenfoot.core.Simulation.runContent(Simulation.java:215)
    at greenfoot.core.Simulation.run(Simulation.java:205)
) first I made help classes (in eclipce) : Server :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
package fejfo;
 
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.List;
 
public class Server implements Runnable {
     
    public final long sleepTime; //try connecting ones per second
    ServerSocket server;
    List<Socket> clients;
    static IOHelp io = new IOHelp();
     
    public Server() throws IOException {
        this(25565,100);
    }
     
    public Server(int port) throws IOException {
        this(port,100);
    }
     
    public Server(long sleepTime) throws IOException {
        this(25565,sleepTime);
    }  
     
    public Server(int port,long sleepTime) throws IOException {
        this.sleepTime = sleepTime;
        try {
            System.out.println("connecting to port " + port);
            server = new ServerSocket(port);
        } catch (IOException e) {
            System.err.println("Could not listen on port: " + port);
            throw e;
        }
        Thread t = new Thread(this);
        t.start();
    }
 
    boolean active = true;
    public void stop() {
        active = false;
    }
     
     
    @Override
    public void run() {
        while(active) {
            try {
                Socket clientSocket = server.accept();
                clients.add(clientSocket);
                 
                for(Socket s : clients) {
                     //PrintWriter out = new PrintWriter(s.getOutputStream(), true);
                     BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
                     String input;
                    while((input = in.readLine()) != null) {
                        String[] parts = input.split(",");
                         for (int i = 0; i < parts.length; i++) {
                            try {
                                String part = parts[i];
                                String nextPart = parts[i+1];
                                if(part == "getOthers") {                              
                                    byte[] clientPort = nextPart.getBytes();
                                    Socket client = null;
                                    for(Socket pClient : clients) {
                                        if(pClient.getLocalAddress().getAddress() == clientPort) {
                                            client = pClient;
                                            break;
                                        }
                                    }
                                    if(client == null) return;
                                    clients.remove(client);
                                    send(clients, clientPort);
                                    clients.add(client);
                                }else if(part == "send" || part == "sendAll") {
                                    send(nextPart);
                                }else if(part == "sendTo") {
                                    byte[] clientPort = nextPart.getBytes();
                                    send(parts[i+2],clientPort);
                                }else {
                                    System.err.println("SERVER:"+s.getLocalAddress().getAddress() +" sended an unknown command :" + input);
                                    send("SERVER: you sended an unknown command :" + input,s.getLocalAddress().getAddress());
                                }
                            }catch(ArrayIndexOutOfBoundsException e) {
                                e.printStackTrace();
                                System.err.println("SERVER: a client sended an invallid command(not enuf parts) :" + input);
                                send("SERVER: a client sended an invallid command(not enuf parts) :" + input);
                            }
                        }
                     }
                }
                 
                try {
                Thread.sleep(sleepTime);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    System.err.println("Thead could not sleep for " + sleepTime);
                }
            } catch (IOException e) {
                System.err.println("could not add an extra client : Accept failed");               
            }
        }      
    }
     
    public void send(Object data) throws IOException {
        String stringForm = io.stringize(data);
        for(Socket s : clients) {
            PrintWriter out = new PrintWriter(s.getOutputStream(), true);
            //BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
            //String inputLine, outputLine;
            out.println(stringForm);
            out.close();       
        }  
    }
 
    public void send(Object data,byte[] targetIP) throws IOException {
        String stringForm = io.stringize(data);
        for(Socket s : clients) {
            if(s.getLocalAddress().getAddress() == targetIP) {
                PrintWriter out = new PrintWriter(s.getOutputStream(), true);
                //BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
                //String inputLine, outputLine;
                out.println(stringForm);
                out.close(); 
            }
        }
     
    }  
}
Client : The Client class :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
package fejfo;
 
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.List;
 
public class Client implements Runnable {
    private Socket socket;
    private PrintWriter out;
    private BufferedReader in;
    public long sleepTime = 100; //check for incomming messages 10 times per second
    public MessageHandler handler;
    private List<Socket> others;
    public static IOHelp io = new IOHelp();
 
    public Client(String ip,MessageHandler m) throws IOException {
        this(ip,25565,m);
    }
 
    public Client(String ip, int port,MessageHandler m) throws IOException {   
         handler = m;
         socket = new Socket(ip, port);
         out = new PrintWriter(socket.getOutputStream(),true);
         in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
         Thread t = new Thread(this);
         t.start();
    }
     
    public Client(String ip,long sleepTime,MessageHandler m) throws IOException {
        this(ip,25565,sleepTime,m);
    }
 
    public Client(String ip, int port,long sleepTime,MessageHandler m) throws IOException {
         handler = m;
         socket = new Socket(ip, port);
         out = new PrintWriter(socket.getOutputStream(),true);
         in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
         this.sleepTime = sleepTime;
         Thread t = new Thread(this);
         t.start();
    }
     
    public void send(Object data) throws IOException {
        out.println("send,"+io.stringize(data));
    }
     
    public void sendTo(byte[] ip,Object data) throws IOException {
        out.println("sendTo,"+ip+io.stringize(data));
    }
     
    public void sendTo(Socket other,Object data) throws IOException {
        out.println("sendTo,"+other.getLocalAddress().getAddress()+io.stringize(data));
    }
 
    boolean active = true;
    @SuppressWarnings("unchecked")
    @Override
    public void run() {
        // Auto-generated method stub
        while(active) {
            try {
                Thread.sleep(sleepTime);
            } catch (InterruptedException e) {
                // Auto-generated catch block
                e.printStackTrace();
            }
            String input;
            try {
                while((input = in.readLine()) != null) {
                    if(io.deSerialize(input) instanceof List<?>) {
                        others = (List<Socket>) io.deSerialize(input);
                    }else handler.reicive(input);
                }
            } catch (IOException e) {
                // Auto-generated catch block
                e.printStackTrace();
            } catch (ClassNotFoundException e) {
                // Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
     
    public void stop() {
        active = false;
    }
     
    public List<Socket> getOthers() {
        return others;
    }
}
The MessageHandler class :
1
2
3
4
5
package fejfo;
 
public abstract interface MessageHandler {
    public abstract void reicive(String data);
}
then I created a very basic test program in Greenfoot the only thing it has is a world
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
import greenfoot.*;  // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
import fejfo.Server;
import javax.swing.JOptionPane;
import fejfo.MessageHandler;
import fejfo.Client;
import java.awt.Color;
import java.io.IOException;
/**
 * Write a description of class Strater here.
 *
 * @author (your name)
 * @version (a version number or a date)
 */
public class Strater extends World implements MessageHandler
{
 
    /**
     * Constructor for objects of class Strater.
     *
     */
    public Strater()
    {   
        // Create a new world with 600x400 cells with a cell size of 1x1 pixels.
        super(600, 400, 1);
        setBackground(new GreenfootImage("press h to host(make a server) or j to join ",30,Color.GREEN,Color.WHITE,Color.GREEN));
        JOptionPane.showMessageDialog(null,"active, press h to host or j to join");
        Greenfoot.start();
    }
 
    boolean made = false;
    boolean joined = false;
    boolean inServerMode = true;
    Server server;
    Client client;
    public void act() {
        if(Greenfoot.isKeyDown("&")) {
            inServerMode = ! inServerMode;
        }else if(Greenfoot.isKeyDown("h") && made == false && inServerMode) {
            made = true;
            int port;
            try {
                port = Integer.parseInt(JOptionPane.showInputDialog("enter port"));
            }catch(NumberFormatException e) {
                e.printStackTrace();
                port = 25565;
            }
            try {
                server = new Server(port,100);
            }catch(IOException e) {
                e.printStackTrace();
            }
        }else if(Greenfoot.isKeyDown("s") && made == true && inServerMode) {
            server.stop();
            server = null;
        }else if(Greenfoot.isKeyDown("j") && joined == false && inServerMode) {
            joined = true;
            String ip = JOptionPane.showInputDialog("enter ip");
            int port;
            try {
                port = Integer.parseInt(JOptionPane.showInputDialog("enter port"));
            }catch(NumberFormatException e) {
                e.printStackTrace();
                port = 25565;
            }
            try {
                client = new Client(ip,port,100,this);
            }catch(IOException e) {
                e.printStackTrace();
            }
        }
        String key = Greenfoot.getKey();
        if(key != null && client != null && joined) {
            try {
                client.send(key);
            }catch(IOException e) {
                e.printStackTrace();
            }
        }
    }
 
    public void reicive(String message) {
        System.out.println("got message : " + message);
    }
}
I had trouble with using my liberarie in greenfoot because my eclipce and greenfoot used differend java versions the server continging to run exporting the greenfoot project to a jar file (still not fixed (It appeared when I update Greenfoot to a version without JDK) and portforwarding you don't need to read all the code to be able to help you can help if you just know what the ConnectException is
fejfo fejfo

2015/8/22

#
sorry for the spelling mistakes
fejfo fejfo

2015/8/23

#
help ?
danpost danpost

2015/8/24

#
Sorry, fejfo. My PM project does not use sockets. It uses the UserInfo storage that greenfoot supplies. The program assigns a number to each new user that becomes their identification number. Then prefixes each message with the id (in character form) of the user that is to receive that message.
fejfo fejfo

2015/8/24

#
ow could I use UserInfo for real time multiplayer then ? (Sockets are to hard)
danpost danpost

2015/8/24

#
fejfo wrote...
could I use UserInfo for real time multiplayer then ? (Sockets are to hard)
For turn-based scenarios, it would not be a problem. With real-time interaction, you will experience lots of lag and tax the server on UserInfo calls (not recommended).
fejfo fejfo

2015/8/24

#
what I'm currently making is not a turn based scenario so I guess I can't use UserInfo but I've tried to work with sockets some more : these are the update versions of my help classes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
package fejfo;
 
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.List;
 
public class Server implements Runnable {
     
    public long sleepTime; //try connecting ones per second
    ServerSocket server;
    ServerConnector connector;
    List<Socket> clients;
    static IOHelp io = new IOHelp();
     
    public Server() throws IOException {
        this(25565,100);
    }
     
    public Server(int port) throws IOException {
        this(port,100);
    }
     
    public Server(long sleepTime) throws IOException {
        this(25565,sleepTime);
    }  
     
    public Server(int port,long sleepTime) throws IOException {
        this.sleepTime = sleepTime;
        try {
            System.out.println("connecting to port " + port);
            server = new ServerSocket(port);
        } catch (IOException e) {
            System.err.println("Could not listen on port: " + port);
            throw e;
        }
        Thread t = new Thread(this);
        t.start();
        connector = new ServerConnector(this);
        t = new Thread(connector);
        t.start();
    }
 
    boolean active = true;
    public void stop() {
        active = false;
        connector.stop();
    }
     
     
@Override
public void run() {
    while(active) {
        try {
            Thread.sleep(sleepTime);
        } catch (InterruptedException e) {
            e.printStackTrace();
            System.err.println("Thead could not sleep for " + sleepTime);
        }  
        if(clients.size() < 1) continue;        
        for(Socket s : clients) {
            //PrintWriter out = new PrintWriter(s.getOutputStream(), true);
            BufferedReader in;
            try {
                in = new BufferedReader(new InputStreamReader(s.getInputStream()));
                String input;
                while((input = in.readLine()) != null) {
                    String[] parts = input.split(",");
                    for (int i = 0; i < parts.length; i++) {
                        try {
                            String part = parts[i];
                            String nextPart = parts[i+1];
                            if(part == "getOthers") {                              
                                byte[] clientPort = nextPart.getBytes();
                                Socket client = null;
                                for(Socket pClient : clients) {
                                    if(pClient.getLocalAddress().getAddress() == clientPort) {
                                        client = pClient;
                                        break;
                                    }
                                }
                                if(client == null) return;
                                    clients.remove(client);
                                    send(clients, clientPort);
                                    clients.add(client);
                                }else if(part == "send" || part == "sendAll") {
                                    send(nextPart);
                                }else if(part == "sendTo") {
                                    byte[] clientPort = nextPart.getBytes();
                                    send(parts[i+2],clientPort);
                                }else {
                                    System.err.println("SERVER:"+s.getLocalAddress().getAddress() +" sended an unknown command :" + input);
                                    send("SERVER: you sended an unknown command :" + input,s.getLocalAddress().getAddress());
                                }
                        }catch(ArrayIndexOutOfBoundsException e) {
                            e.printStackTrace();
                            System.err.println("SERVER: a client sended an invallid command(not enuf parts) :" + input);
                            send("SERVER: a client sended an invallid command(not enuf parts) :" + input);
                        }
                    }
                }
            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
              
        }
    }  
}      
 
     
    public void send(Object data) throws IOException {
        String stringForm = io.stringize(data);
        for(Socket s : clients) {
            PrintWriter out = new PrintWriter(s.getOutputStream(), true);
            //BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
            //String inputLine, outputLine;
            out.println(stringForm);
            out.close();       
        }  
    }
 
    public void send(Object data,byte[] targetIP) throws IOException {
        String stringForm = io.stringize(data);
        for(Socket s : clients) {
            if(s.getLocalAddress().getAddress() == targetIP) {
                PrintWriter out = new PrintWriter(s.getOutputStream(), true);
                //BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
                //String inputLine, outputLine;
                out.println(stringForm);
                out.close(); 
            }
        }
     
    }  
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
package fejfo;
 
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.List;
 
public class Client implements Runnable {
    private Socket socket;
    private PrintWriter out;
    private BufferedReader in;
    public long sleepTime = 100; //check for incomming messages 10 times per second
    public MessageHandler handler;
    private List<Socket> others;
    public static IOHelp io = new IOHelp();
 
    public Client(String ip,MessageHandler m) throws IOException {
        this(ip,25565,m);
    }
 
    public Client(String ip, int port,MessageHandler m) throws IOException {   
         handler = m;
         socket = new Socket(ip, port);
         out = new PrintWriter(socket.getOutputStream(),true);
         in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
         Thread t = new Thread(this);
         t.start();
    }
     
    public Client(String ip,long sleepTime,MessageHandler m) throws IOException {
        this(ip,25565,sleepTime,m);
    }
 
    public Client(String ip, int port,long sleepTime,MessageHandler m) throws IOException {
         handler = m;
         socket = new Socket(ip, port);
         out = new PrintWriter(socket.getOutputStream(),true);
         in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
         this.sleepTime = sleepTime;
         Thread t = new Thread(this);
         t.start();
    }
     
    public void send(Object data) throws IOException {
        out.println("send,"+io.stringize(data));
    }
     
    public void sendTo(byte[] ip,Object data) throws IOException {
        out.println("sendTo,"+ip+io.stringize(data));
    }
     
    public void sendTo(Socket other,Object data) throws IOException {
        out.println("sendTo,"+other.getLocalAddress().getAddress()+io.stringize(data));
    }
 
    boolean active = true;
    @SuppressWarnings("unchecked")
    @Override
    public void run() {
        // Auto-generated method stub
        while(active) {
            try {
                Thread.sleep(sleepTime);
            } catch (InterruptedException e) {
                // Auto-generated catch block
                e.printStackTrace();
            }
            String input;
            try {
                while((input = in.readLine()) != null) {
                    if(io.deSerialize(input) instanceof List<?>) {
                        others = (List<Socket>) io.deSerialize(input);
                    }else handler.reicive(input);
                }
            } catch (IOException e) {
                // Auto-generated catch block
                e.printStackTrace();
            } catch (ClassNotFoundException e) {
                // Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
     
    public void stop() {
        active = false;
    }
     
    public List<Socket> getOthers() {
        return others;
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
package fejfo;
 
import java.io.IOException;
import java.net.Socket;
 
public class ServerConnector implements Runnable{
 
    public Server s;
     
    public ServerConnector(Server s) {
        // TODO Auto-generated constructor stub
    }
 
    @Override
    public void run() {
        while(active) {
            try {
                Thread.sleep(s.sleepTime);
            } catch (InterruptedException e) {
                //Auto-generated catch block
                e.printStackTrace();
            }
             
            Socket clientSocket;
            try {
                clientSocket = s.server.accept();
                s.clients.add(clientSocket);
            } catch (IOException e) {
                //Auto-generated catch block
                e.printStackTrace();           
            }
             
        }
         
    }
     
    boolean active = true;
    public void stop() {
        active = false;
    }
     
    public void restart() {
        active = true;
        run();
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
import greenfoot.*;  // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
import fejfo.Server;
import javax.swing.JOptionPane;
import fejfo.MessageHandler;
import fejfo.Client;
import java.awt.Color;
import java.io.IOException;
/**
 * Write a description of class Strater here.
 *
 * @author (your name)
 * @version (a version number or a date)
 */
public class Strater extends World implements MessageHandler
{
 
    /**
     * Constructor for objects of class Strater.
     *
     */
    public Strater()
    {   
        // Create a new world with 600x400 cells with a cell size of 1x1 pixels.
        super(600, 400, 1);
        setBackground(new GreenfootImage("press h to host(make a server) or j to join ",30,Color.GREEN,Color.WHITE,Color.GREEN));
        JOptionPane.showMessageDialog(null,"active, press h to host or j to join");
        Greenfoot.start();
    }
 
    boolean made = false;
    boolean joined = false;
    boolean inServerMode = true;
    Server server;
    Client client;
    public void act() {
        if(Greenfoot.isKeyDown("&")) {
            inServerMode = ! inServerMode;
        }else if(Greenfoot.isKeyDown("h") && made == false && inServerMode) {
            made = true;
            int port;
            try {
                port = Integer.parseInt(JOptionPane.showInputDialog("enter port"));
            }catch(NumberFormatException e) {
                e.printStackTrace();
                port = 25565;
            }
            try {
                server = new Server(port,100);
            }catch(IOException e) {
                e.printStackTrace();
            }
        }else if(Greenfoot.isKeyDown("s") && made == true && inServerMode) {
            server.stop();
            server = null;
            client.stop();
            client = null;
            made = false;
            joined = false;
        }else if(Greenfoot.isKeyDown("j") && joined == false && inServerMode) {
            joined = true;
            String ip = JOptionPane.showInputDialog("enter ip");
            int port;
            try {
                port = Integer.parseInt(JOptionPane.showInputDialog("enter port"));
            }catch(NumberFormatException e) {
                e.printStackTrace();
                port = 25565;
            }
            try {
                client = new Client(ip,port,100,this);
            }catch(IOException e) {
                e.printStackTrace();
                System.err.println("Exception:"+e.getCause());
            }
        }
        String key = Greenfoot.getKey();
        if(key != null && client != null && joined) {
            try {
                client.send(key);
            }catch(IOException e) {
                e.printStackTrace();
            }
        }
    }
     
    public void stopped() {
        server.stop();
        server = null;
        client.stop();
        client = null;
        made = false;
        joined = false;
    }
 
    public void reicive(String message) {
        System.out.println("got message : " + message);
    }
}
fejfo fejfo

2015/8/24

#
but it seems like I've made it worse I don't even get the ConnectException any more it crashes now right after I enter the port for make the server I get
1
2
3
4
5
6
7
8
9
10
11
12
13
java.lang.NullPointerException
    at Strater.stopped(Strater.java:87)
    at greenfoot.core.Simulation.worldStopped(Simulation.java:284)
    at greenfoot.core.Simulation.signalStopping(Simulation.java:447)
    at greenfoot.core.Simulation.maybePause(Simulation.java:326)
    at greenfoot.core.Simulation.runContent(Simulation.java:212)
    at greenfoot.core.Simulation.run(Simulation.java:205)
Exception in thread "Thread-23" java.lang.NullPointerException
    at fejfo.ServerConnector.run(ServerConnector.java:18)
    at java.lang.Thread.run(Thread.java:745)
Exception in thread "Thread-22" java.lang.NullPointerException
    at fejfo.Server.run(Server.java:63)
    at java.lang.Thread.run(Thread.java:745)
I know how to fix the null pointer exception but the thread exceptions ?
1
2
3
4
5
6
7
8
public void stopped() {
        if(server != null) server.stop();
        server = null;
        if(client != null) client.stop();
        client = null;
        made = false;
        joined = false;
    }
shoud have fixed them
davmac davmac

2015/8/24

#
fejfo wrote...
I know how to fix the null pointer exception but the thread exceptions ?
The only exceptions that you're getting are null pointer exceptions. Look at the stack traces again. Looking at your ServerConnector constructor:
1
2
3
public ServerConnector(Server s) {
    // TODO Auto-generated constructor stub
}
Shouldn't you be saving the Server instance 's' somewhere (i.e. in instance variable 'server')? That instance variable shouldn't be public btw (it's bad practice to expose sensitive variables).
fejfo fejfo

2015/8/24

#
ow I forgot to save the server instance so stupid
fejfo fejfo

2015/8/24

#
I have :
1
2
3
public ServerConnector(Server s) {
        this.s = s;
    }
davmac davmac

2015/8/24

#
Ok, so the problem's gone now?
fejfo fejfo

2015/8/24

#
there was an other problem in Server to I didn't initialize "clients"
1
List<Socket> clients = new ArrayList<Socket>();
(is there anny negative effect off diffing clients as a List instead of an ArrayList ? and I still have the jave.net.ConnectException (I don't really think it is bad coding but just bad portforwarding or so but I don't know)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
java.net.ConnectException: Connection refused: connect
    at java.net.DualStackPlainSocketImpl.connect0(Native Method)
    at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:79)
    at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
    at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
    at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
    at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
    at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
    at java.net.Socket.connect(Socket.java:589)
    at java.net.Socket.connect(Socket.java:538)
    at java.net.Socket.<init>(Socket.java:434)
    at java.net.Socket.<init>(Socket.java:211)
    at fejfo.Client.<init>(Client.java:38)
    at Strater.act(Strater.java:74)
    at greenfoot.core.Simulation.actWorld(Simulation.java:600)
    at greenfoot.core.Simulation.runOneLoop(Simulation.java:535)
    at greenfoot.core.Simulation.runContent(Simulation.java:215)
    at greenfoot.core.Simulation.run(Simulation.java:205)
Exception:null
sorry I didn't answer immedialy I had to leave
danpost danpost

2015/8/24

#
There is no problem with having 'clients' declared as a List instead of an ArrayList. However, being the List class is an interface, you cannot directly create a List from that class. There would be no issues in typing a field or variable as List instead of ArrayList; You can always be more specific as to its type when needed. For example, with 'clients' declared as a List object and created from the ArrayList class:
1
((ArrayList)clients).trimToSize();
Most methods you would usually use come from the List interface, however.
fejfo fejfo

2015/8/24

#
nice to know I thought List was the super class thanks for the info (danpost and davmac)
There are more replies on the next page.
1
2