I'm making a game and I want to establish a network connection between 2 players through a server.
So far all I have is:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class Server extends Thread {
public ServerSocket s;
public Socket p1, p2;
public PrintWriter bis1, bis2;
public BufferedReader bos1, bos2;
public Server() {
try {
s = new ServerSocket(5_000, 1714);
} catch (IOException e) {
e.printStackTrace();
}
}
public void run() {
try {
p1 = s.accept();
p2 = s.accept();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
bis1 = new PrintWriter(p1.getOutputStream());
bis2 = new PrintWriter(p2.getOutputStream());
bos1 = new BufferedReader(new InputStreamReader(p1.getInputStream()));
bos2 = new BufferedReader(new InputStreamReader(p2.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
}
while (p1.isClosed() || p2.isClosed()) { // if one of the players disconnect, the match will end.
try {
String p1 = bos1.readLine(); // what p1 says
String p2 = bos2.readLine(); // what p2 says
if (!p1.equalsIgnoreCase("")) { // if what p1 says is something
if(p1.startsWith("my position x=")) {
p1 = p1.substring(15);
float x = Float.parseFloat(p1);
bis2.write("his position x=" + x);
} else if(p1.startsWith("my position y=")) {
p1 = p1.substring(15);
float y = Float.parseFloat(p1);
bis2.write("his position y=" + y);
}
}
if (!p2.equalsIgnoreCase("")) { // if what p1 says is something
if(p2.startsWith("my position x=")) {
p2 = p2.substring(15);
float x = Float.parseFloat(p2);
bis1.write("his position x=" + x);
} else if(p2.startsWith("my position y=")) {
p2 = p2.substring(15);
float y = Float.parseFloat(p2);
bis1.write("his position y=" + y);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
This is meant to send update of the players x and y to each other.
I'll implement other data of the game later but I want to know if I'm going in the right direction.