I'm trying to make a simple network game using a client and server.
Currently I have two threads running for both my client and server: - The Main thread which calculates player positions, physics, draws things to the screen, etc. - The Client/Server thread which handles sending/receiving of datagrams from/to the server or from/to the client
The reason I have two threads for each is because the receive() method call is BLOCKING, so I don't want it to block any of my gameplay while its waiting for a new datagram.
This works absolutely fine until I get to the point where I want to be able to send a datagram in my main thread.
EXAMPLE
In the client, in my main thread, I have a keypress event where when my client presses the 'z' key, it sends a datagram to the server as a test. However, the program just completely stalls, no exceptions. It stalls to the point where I need to close it via task manager in Windows.
The socket I'm using to send to is declared and initialized in my ClientThread class (which extends Thread). It gets initialized when run() is called in my ClientThread:
public void run() {
try {
// Construct the socket
socket = new DatagramSocket();
...
I can easily send datagrams in my ClientThread/ServerThread, but when I try to send them in my MainThread at any given time (e.g. when a client presses Z and wants to send a test message), the program stalls/crashes.
Why is it crashing and what can I do to fix this?
Is it okay to use one thread for receiving/sending, and another thread for doing other calculations but also including sending datagrams at any given time? (e.g. when a player presses the 'z' key or something else).
I have a feeling it has something to do with the fact that the DatagramSocket is declared and initialized inside the ClientThread/ServerThread class
and the MainThread is trying to gain access to it at any given time it wants (again, when a player presses the 'z' key for example).