So, I'm fairly new to sockets and data streams... And I am absolutely baffled by this issue I'm having. I've searched for hours trying to find a solution, assuming that other people might have had the same issue I'm having, but I've found absolutely nothing helpful so far.
I'm writing a very simple multithreaded server/client program that is supposed to open a serverSocket, and accept connections from clients, storing them in a simple arraylist (I'll change the storage process once I actually get messages to send), and then a message handler thread parses the list, and checks if a user has written to the server. If the user has written something, the program then displays the resulting message to the console. My program successfully writes to the server socket through the DataOutputStream, but when I attempt to read from the corresponding DataInputStream on the server side, it says the stream is empty, and my program will continue to loop. I've checked that the DataOutputStream receives the data through DataOutputStream.size(), and that the DataInputStream I am attempting to read data from corresponds to the correct DataOutputStream I mentioned before.
User Code:
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.SocketException;
public class User {
private String hashID;
private Socket connection;
private static int hashVal = 0;
DataInputStream consoleInputStream;
String consoleInput = "";
public User(Socket conn) throws SocketException {
hashID = hashUserKey();
connection = conn;
connection.setSoTimeout(1500);
consoleInputStream = new DataInputStream(System.in);
}
private static String hashUserKey() { //placeholder for now
hashVal++;
return("Guest" + hashVal);
}
public Socket getSocket() {
return this.connection;
}
public String getID() {
return this.hashID;
}
public boolean disconnect() {
try {
consoleInputStream.close();
connection.close();
return true;
} catch (IOException e) {
System.err.println(hashID + " was unable to successfully disconnect");
return false;
}
}
public void startConnection() {
new Thread() {
#Override
public void run() {
while(!connection.isClosed()) {
try {
consoleInput = consoleInputStream.readLine();
if(consoleInput != null || consoleInput != "") {
writeToServer(consoleInput);
}
} catch (IOException e) {
System.err.println("Was not able to read console input");
}
}
System.out.println("You were disconnected, have a nice day!");
return;
}
}.start();
}
private boolean writeToServer(String toWrite) {
try {
String msg = hashID + ">>>: " + toWrite;
DataOutputStream outStream = new DataOutputStream(connection.getOutputStream());
outStream.writeUTF(toWrite + "\r\n");
outStream.flush();
consoleInput = "";
System.out.println(msg + "\t was written to " + connection.getInetAddress() + ":" + connection.getPort());
return true;
} catch (IOException e) {
System.err.println(hashID + " was unable to write to server");
return false;
}
}
#Override
public boolean equals(Object o) {
User t = (User) o;
if(t.hashID == this.hashID) {
return true;
}
return false;
}
}
Server Code:
import java.net.*;
import java.io.*;
import java.util.*;
public class TestServer {
private static ServerSocket server;
private static TestLogger logger;
private static Thread serverHandlerThread;
private static Thread messageHandlerThread;
private static ArrayList<User> users;
private static volatile boolean hasBeenStopped = false;
public static boolean startServer(int port) {
logger = new TestLogger();
logger.log("Attempting to create default shutdown behavior for server");
Runtime.getRuntime().addShutdownHook(new Thread() {
#Override
public void run() {
if(!hasBeenStopped) {
logger.warn("Server was shut down without running stopServer(), running by default");
stopServer();
}
}
}
);
logger.log("Shutdown behaivor created. Now attempting to set up user database"/*TODO create a real database*/);
users = new ArrayList<User>();
logger.log("Attempting to start server");
try {
server = new ServerSocket(port);
logger.log("Server successfully started at " + server.getInetAddress() + ":" + server.getLocalPort() +", now attempting to start user connection handler");
serverHandlerThread = new Thread() {
#Override
public void run() {
this.setName("serverHandlerThread");
while(!server.isClosed()) {
try {
Socket temp = server.accept();
logger.log("Connection accepted from " + temp.getInetAddress());
System.out.println("Connection accepted from " + temp.getInetAddress());
startUserConnection(new User(temp));
} catch (SocketException e) {
logger.warn("Server was closed while in accept phase");
} catch (IOException e) {
e.printStackTrace();
}
}
logger.log(this.getName() + " was stopped, server socket was closed successfully");
return;
}
};
serverHandlerThread.start();
logger.log("Server thread successfully started, listening for connections on: " + server.getInetAddress().toString() + ":" + port);
logger.log("Attempting to start message handler thread to read user inputs");
messageHandlerThread = new Thread() {
#Override
public void run() {
this.setName("messageHandlerThread");
while(!server.isClosed()) {
if(users.isEmpty()) {
continue;
}
for(int i = 0; i < users.size(); i++) {
User temp = users.get(i);
try {
System.out.println(new DataInputStream(temp.getSocket().getInputStream()).readUTF());
} catch (IOException e) {
System.err.println("Nothing to read from client: " + temp.getID());
}
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
};
messageHandlerThread.start();
return true;
} catch (IOException e) {
logger.error("Could not bind server socket to port.");
return false;
}
}
public static boolean stopServer() {
logger.log("Started shut down process");
if(serverHandlerThread == null || !serverHandlerThread.isAlive()) {
logger.warn("Thread has not been started yet or has already been killed");
return false;
}
else {
stopAllUserConnections();
try {
server.close();
hasBeenStopped = true;
while(serverHandlerThread.isAlive()) {
}
logger.log("Server was successfully shut down");
return true;
} catch (IOException e) {
logger.error("Could not close server socket");
return false;
}
}
}
private static void startUserConnection(User user) {
logger.log("Connected new user from " + user.getSocket().getInetAddress());
users.add(user);
System.out.println(user.getID() + " was added to list");
user.startConnection();
}
private static boolean stopUserConnection(User user) {
logger.log("Attempting to disconnect user, address: " + user.getSocket().getInetAddress());
for(User u : users) {
if(u.equals(user)) {
u.disconnect();
return true;
}
}
logger.warn("Could not find user with address: " + user.getSocket().getInetAddress());
return false;
}
private static boolean stopAllUserConnections() {
logger.log("Attempting to disconnect all users from the server");
if(users.isEmpty()) {
logger.warn("No users available to disconnect");
return false;
}
for(User u : users) {
u.disconnect();
}
users.clear();
return true;
}
public static void main(String args[]) {
startServer(*the_port*);
Client c = new Client();
c.connect("0.0.0.0", *the_port*);
}
}
Client Code:
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
public class Client {
public boolean connect(String serverName, int port) {
try {
System.out.println("Attempting to connect");
Socket sock = new Socket(serverName, port);
System.out.println("Connected");
return true;
} catch (UnknownHostException e) {
System.err.println("Could not resolve " + serverName + ":" + port);
}
catch (IOException e) {
e.printStackTrace();
}
return false;
}
}
So as I said above, this works fine up until I attempt to read the data written to the server. No matter what I do, the server's call to readUTF() on the socket always throws an IOException and checking the bytes ready to read by using DataInputStream.available() returns 0 as well. My sample output from my most recent run is as follows:
Attempting to connect
Connected
Connection accepted from *the_address*
Guest1 was added to list
Nothing to read from client: Guest1
Nothing to read from client: Guest1
Nothing to read from client: Guest1
test
Guest1>>>: test was written to *the_address:another_port*
Nothing to read from client: Guest1
Nothing to read from client: Guest1
Nothing to read from client: Guest1
I know my code may be terribly optimized, and I'll work on fixing that later, but right now, all I want to know is why my DataInputStream is empty after flushing the corresponding DataOutputStream, and how I can successfully send UTF data between them.
Related
Explanation
I'm currently trying to create a Multiplayer Game with Java where up to five Players can play together.
The problem is that when I'm trying to connect multiple Clients to my Server I get an Exception and the Server doesn't work anymore.
With one Client at a time, everything works fine.
So what I need is a Server that can handle up to five players at a time and the clients should always get some new game data from the Server
every few seconds (Connected Players, etc.).
The "Game data" in the code below is the String I'm sending through the Object Stream.
Normally I would send an Object which has all the game data, but with the String, I get the same problem.
I'm struggling with the problem that only one Client can connect without any errors occurring for some days now and I didn't find a solution to my problem.
I saw that there are things like java.nio or the ExecutorService, but I didn't really understand those that much, so I don't know if they can help.
I have made a smaller program that simulates the same problem I get with my bigger program.
To Start the Server, you need to Start the GameMultiPlayerCreate.java Class, and for the Client, the Client.java class.
I'm new to Sockets so if something is unnecessary or if something can be made better please let me know.
So the Error I'm getting when I connect two or more Clients is:
java.io.StreamCorruptedException: invalid stream header: 00050131
at java.io.ObjectInputStream.readStreamHeader(Unknown Source)
at java.io.ObjectInputStream.<init>(Unknown Source)
at Server.waitForData(Server.java:89) //I highlighted that in the code with a comment
at Server.loopWaitForData(Server.java:49)
at Server.run(Server.java:34)
at java.lang.Thread.run(Unknown Source)
Code
GameMultiPlayerCreate.java: Should start the Server threads if a Client connects
public class GameMultiPlayerCreate {
ServerSocket socketServer = null;
static String settingIp = "localhost";
static String settingPort = "22222";
static byte settingPlayers = 5;
public static int connectedPlayers = 0;
public static void main(String[] args) {
try {
GameMultiPlayerCreate objGameMultiPlayerCreate = new GameMultiPlayerCreate();
objGameMultiPlayerCreate.createServer();
} catch (NumberFormatException | IOException | InterruptedException e) {
e.printStackTrace();
}
}
public void createServer() throws NumberFormatException, UnknownHostException, IOException, InterruptedException {
while (connectedPlayers < settingPlayers) {
socketServer = new ServerSocket(Integer.parseInt(settingPort), 8, InetAddress.getByName(settingIp));
System.out.println("Server is waiting for connection...");
Socket socket = socketServer.accept();
new Thread(new Server(socket)).start();
Thread.sleep(5000);
socketServer.close();
}
}
}
Server.java: This is the Class of which a new Thread should be created for each connected Client (Client Handler)
public class Server implements Runnable {
protected static Socket socket = null;
private int loops;
private int maxLoops = 10;
private int timeout = 10000;
protected static boolean killThread = false;
private boolean authenticated = true; //true for testing
protected static String ip;
protected static int port;
public Server(Socket socket) throws IOException {
Server.socket = socket;
}
public void run() {
try {
socket.setSoTimeout(timeout);
} catch (SocketException e) {
System.out.println("Error while trying to set Socket timeout. ");
System.out.println("Closing Thread..." + Thread.currentThread());
disconnectClient();
}
if (!killThread) {
GameMultiPlayerCreate.connectedPlayers = GameMultiPlayerCreate.connectedPlayers + 1;
loopWaitForData();
}
}
private void disconnectClient() {
System.out.println("Kicking Client... " + Thread.currentThread());
killThread = true;
GameMultiPlayerCreate.connectedPlayers = GameMultiPlayerCreate.connectedPlayers - 1;
}
public void loopWaitForData() {
while (!killThread) {
System.out.println(maxLoops + ", " + loops);
if (maxLoops - loops > 0) {
try {
waitForData();
} catch (SocketTimeoutException e) {
System.out.println("Error occurred while waiting for Data. Thread disconnected? Sending reminder. " + Thread.currentThread());
if (!authenticated) {
System.out.println("Kicking Client: Not authenticated");
disconnectClient();
} else {
commandReminder();
}
} catch (ClassNotFoundException | IOException e) {
loops = loops + 1;
System.out.println("Error occurred while waiting for Data. Waiting for more Data. " + Thread.currentThread());
e.printStackTrace();
loopWaitForData();
}
} else if (maxLoops - loops == 0) {
System.out.println("Error occurred while waiting for Data. Maximum trys reached. Disbanding connection. " + Thread.currentThread());
disconnectClient();
loops = loops + 1;
} else {
System.out.println("Closing Thread..." + Thread.currentThread());
disconnectClient();
}
}
}
private void commandReminder() {
System.out.println("Reminder");
try {
String code = new String("0");
ObjectOutputStream outputObject = new ObjectOutputStream(Server.socket.getOutputStream());
outputObject.writeObject(code);
} catch (IOException e) {
System.out.println("Error occurred while trying to authenticate Client: " + e + " in " + Thread.currentThread());
}
}
public void waitForData() throws IOException, ClassNotFoundException {
String code;
System.out.println("Waiting for Data...");
//Next line is where the error occurres
ObjectInputStream inputObject = new ObjectInputStream(socket.getInputStream());
while ((code = (String) inputObject.readObject()) != null) {
System.out.println("Received Data...");
System.out.println("Input received: " + code);
return;
}
}
}
Client.java: This is the Client
public class Client {
public static Socket socket = new Socket();
private int loops = 0;
private int maxLoops = 10;
private static boolean killThread = false;
private String ip;
private int port;
public Client(String receivedIp, String receivedPort) {
ip = receivedIp;
port = Integer.parseInt(receivedPort);
try {
System.out.println("Trying to connect to Server...");
socket.connect(new InetSocketAddress(ip, port));
System.out.println("Connected!");
} catch (IOException e) {
System.out.println("Error occurred while trying to connect to Server.");
}
loopWaitForData();
}
public static void main(String[] args) {
#SuppressWarnings("unused")
Client objClient = new Client("localhost", "22222");
}
public void loopWaitForData() {
while (!killThread) {
System.out.println(maxLoops + ", " + loops);
if (maxLoops - loops > 0) {
try {
waitForData();
} catch (IOException | ClassNotFoundException e) {
loops = loops + 1;
try {
Thread.sleep(2000);
} catch (InterruptedException e1) {
}
System.out.println("Error occurred while waiting for Data. Waiting for more Data. " + Thread.currentThread());
e.printStackTrace();
loopWaitForData();
}
} else if (maxLoops - loops == 0){
System.out.println("Error occurred while waiting for Data. Maximum trys reached. Disbanding connection. " + Thread.currentThread());
try {
socket.close();
} catch (IOException e) {
System.out.println("Failed to close Socket " + Thread.currentThread());
}
loops = loops + 1;
} else {
System.out.println("Closing Thread..." + Thread.currentThread());
killThread = true;
}
}
}
public void waitForData() throws IOException, ClassNotFoundException {
InputStream input = socket.getInputStream();
ObjectInputStream inputObject = new ObjectInputStream(input);
String code;
System.out.println("Waiting for Data...");
while ((code = (String) inputObject.readObject()) != null) {
System.out.println("Received Data...");
System.out.println("Input received: " + code);
answer();
return;
}
}
private void answer() {
try {
String code = new String("1");
ObjectOutputStream outputObject = new ObjectOutputStream(socket.getOutputStream());
outputObject.writeObject(code);
} catch (IOException e) {
System.out.println("Error occurred while trying to answer: " + e + " in " + Thread.currentThread());
}
}
}
I have created a Java socket server which creates a socket server on a specified port and then spawns a RecordWriter object to perform some operation on the data stream obtained from each connection.
I start the program with port as 61000 and numthreads as 2.
I also started 3 clients to connect to it.
On the client side I could see that all 3 of them connected to the receiver however, the receiver logs indicated only two of them connected.
netstat -an|grep 61000|grep -i ESTABLISHED
indicated total 6 connections as the client and server are being run on the same machine.
My doubts are:
Why does the client log for the third time show that it could connect to the program on 61000 while I am using the backlog of 2. Also Executors.newFixedThreadPool(numThreads); is allowing only 2 clients to be connected.
Although the server.accept happens in the MyWriter.java and there is no indication in logs that the 3rd client could connect, why does netstat show this as an Established connection
Here are my codes:
MyReceiver.java
package com.vikas;
import java.net.ServerSocket;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class MyReceiver{
protected int serverPort = -1;
protected int numThreads = -1;
protected boolean isStopped = false;
protected Thread runningThread = null;
protected ExecutorService threadPool = null;
protected static Logger logger = LogManager.getLogger(MyReceiver.class);
protected static ServerSocket serverSocket = null;
protected static Map<String, String> mapConnections = new ConcurrentHashMap<String, String>();
public MyReceiver(int port){
this.serverPort = port;
}
public void run(int numThreads){
this.threadPool = Executors.newFixedThreadPool(numThreads);
try {
logger.info("Starting server on port " + this.serverPort);
MyReceiver.serverSocket = new ServerSocket(this.serverPort, numThreads);
} catch (IOException e) {
//throw new RuntimeException("Cannot open port " + this.serverPort, e);
logger.error("Cannot open port " + this.serverPort, e);
}
while(!isStopped()){
this.threadPool.execute(new MyWriter());
}
if(MyReceiver.mapConnections.isEmpty()){
this.threadPool.shutdown();
//System.out.println("Server Stopped after shutdown.") ;
logger.info("Server Stopped after shutdown.");
}
}
public synchronized boolean isStopped() {
return this.isStopped;
}
public synchronized void stop(){
this.isStopped = true;
try {
MyReceiver.serverSocket.close();
} catch (IOException e) {
//throw new RuntimeException("Error closing server", e);
logger.error("Error closing server", e);
}
}
public static void main(String[] args) {
if(args.length != 2){
System.out.println("Number of input arguements is not equal to 4.");
System.out.println("Usage: java -cp YOUR_CLASSPATH -Dlog4j.configurationFile=/path/to/log4j2.xml com.vikas.MyReceiver <port> <number of threads>");
System.out.println("java -cp \"$CLASSPATH:./MyReceiver.jar:./log4j-api-2.6.2.jar:./log4j-core-2.6.2.jar\" -Dlog4j.configurationFile=log4j2.xml com.vikas.MyReceiver 61000 2");
}
int port = Integer.parseInt(args[0].trim());
int numThreads = Integer.parseInt(args[1].trim());
final MyReceiver myConnection = new MyReceiver(port, topic, brokers);
myConnection.run(numThreads);
/*Thread t = new Thread(myConnection);
t.start();*/
try {
Thread.sleep(20000);
} catch (InterruptedException e) {
//e.printStackTrace();
logger.error("Something went wrong", e);
}
//System.out.println("Stopping Server");
Runtime.getRuntime().addShutdownHook(new Thread()
{
#Override
public void run()
{
logger.info("SocketServer - Receive SIGINT!!!");
logger.info("Stopping Server");
if(!myConnection.isStopped()){
myConnection.stop();
}
logger.info("Server Stopped successfully");
try
{
Thread.sleep(1000);
}
catch (Exception e) {}
}
});
//myConnection.stop();
}
}
MyWriter.java
package com.vikas;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.IOException;
import java.net.Socket;
import java.util.Properties;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class MyWriter implements Runnable{
protected String topic = null;
protected String brokers = null;
protected static Logger logger = LogManager.getLogger(MyWriter.class);
public MyWriter () {
}
public void run() {
while(!MyReceiver.serverSocket.isClosed()){
Socket server = null;
try {
server = MyReceiver.serverSocket.accept();
//System.out.println("Just connected to " + server.getRemoteSocketAddress());
logger.info("Just connected to " + server.getRemoteSocketAddress());
MyReceiver.mapConnections.put(server.getRemoteSocketAddress().toString().trim(), "");
//change for prod deployment //change implemented
String key = null;
String message = null;
char ch;
StringBuilder msg = new StringBuilder();
int value = 0;
try {
BufferedReader in = new BufferedReader(new InputStreamReader(server.getInputStream()));
while((value = in.read()) != -1){
ch = (char)value;
if(ch == 0x0a){
//msg.append(ch);
//System.out.println(msg);
message = msg.toString().trim();
//code change as part of testing in prod
if(message.length() != 0){
//do something
msg.setLength(0);
}
else{
logger.error("Blank String received");
msg.setLength(0);
}
}
else{
msg.append(ch);
}
}
logger.info("Closing connection for client :" + server.getRemoteSocketAddress());
//System.out.println("Closing connection for client :" + this.getClientSocket().getRemoteSocketAddress());
server.close();
MyReceiver.mapConnections.remove(server.getRemoteSocketAddress());
} catch (IOException e) {
//report exception somewhere.
//e.printStackTrace();
logger.error("Something went wrong!!", e);
}
finally{
producer.close();
}
} catch (IOException e) {
if(MyReceiver.serverSocket.isClosed()) {
//System.out.println("Server was found to be Stopped.");
logger.error("Server was found to be Stopped.");
logger.error("Error accepting client connection", e);
break;
}
}
}
}
}
The backlog parameter of the ServerSocket constructor restricts the size of the incoming connection queue not the total number of times you are allowed to successfully call accept(). If you want to restrict the number of active connections you need to keep track of how many connections you've accepted then when you hit your threshold don't call accept() again until at least one of the active connections has been closed.
while(!MyReceiver.serverSocket.isClosed()){
Socket server = null;
try {
server = MyReceiver.serverSocket.accept();
//System.out.println("Just connected to " + server.getRemoteSocketAddress());
logger.info("Just connected to " + server.getRemoteSocketAddress());
MyReceiver.mapConnections.put(server.getRemoteSocketAddress().toString().trim(), "");
if (activeConnections == maxConnections) break; // exit accept loop
I've been struggling lately to find a way to deliver strings through a socket file. I'm planning to create a remote tool(client) to execute things based on the received message(server).
I've searched answers for my problem on google and i found some things and managed to understand things but I also got some problems (i'm new to programming, not yet in college).
I would appreciate any help in this matter
SocketService.java ---- class file = serverside
package socket;
import java.io.DataInputStream;
import java.io.EOFException;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.concurrent.TimeUnit;
public class ServiceSocket {
static ServerSocket myService;
static Socket thesocket;
static Thread socketThread;
public static boolean socketRunning;
public static DataInputStream socketMessage;
public static void initialise(String localhost, int portNumber ){
// make a server socket//////
try {
myService = new ServerSocket(portNumber);
System.out.println();
} catch (IOException e) {
e.printStackTrace();
}
//////////////////////////////
}
public static void deploySocket(){
socketThread = new Thread() {
public void run(){
// making connection
System.out.println("VVaiting for connection...");
try {
thesocket = myService.accept();
System.out.println("Connection made");
socketRunning = true;
} catch (IOException e) {
e.printStackTrace();
}
////////////////////////////////////
try {
StartBrain();
} catch (IOException e1) {
e1.printStackTrace();
}
if(socketRunning = false) {
try {
thesocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
};
socketThread.start();
}
public static String getSocketMessage() throws IOException {
try {
socketMessage = new DataInputStream(thesocket.getInputStream());
} catch (IOException e1) {
e1.printStackTrace();
}
boolean looprunning = true;
String message = null;
System.out.println("entering loop");
do {
try {
while (socketMessage.readUTF() != null) {
message = socketMessage.readUTF();
looprunning = false;
}
} catch (EOFException e) {
}
}while(looprunning);
System.out.println("Message received from UTF: " + message);
System.out.println("loop exited vvith message");
if(message == null) {
message = "no message";
}
return message;
}
public static void StartBrain() throws IOException {
System.out.println("socket brain started");
String BrainMessage = getSocketMessage();
if(BrainMessage == "command") {
System.out.println("Command EXECUTED HAHA");
} else if(BrainMessage == "taskschedule") {
System.out.println("task scheduled");
} else {
System.out.println("no command received");
}
}
Main.java ----- class file = serverside
package main;
import socket.ServiceSocket;
public class Main {
public static void main(String[] args) {
ServiceSocket.initialise("localhost", 3535);
ServiceSocket.deploySocket();
}
}
}
Main.java = CLIENT
package mainPackage;
import java.io.*;
import java.net.*;
import java.util.concurrent.TimeUnit;
public class Main {
private static Socket clientSocket;
public static void sendMessage(String message) throws IOException, InterruptedException {
DataOutputStream dOut = new DataOutputStream(Main.clientSocket.getOutputStream());
dOut.writeUTF(message);
dOut.flush();
dOut.close();
}
public static void main(String[] args) throws Exception {
// String modifiedSentence;
clientSocket = new Socket("localhost", 3535);
System.out.println("Initializing");
sendMessage("command");
boolean running = true;
while(running) {
TimeUnit.SECONDS.sleep(3);
sendMessage("taskschedule");
}
clientSocket.close();
}
}
main problem
do {
try {
while (socketMessage.readUTF() != null) {
message = socketMessage.readUTF();
looprunning = false;
}
} catch (EOFException e) {
}
}while(looprunning);
it doesn't read the string/UTF
It does read it, here:
while (socketMessage.readUTF() != null) {
and then throws it away as you're not assigning the return-value to a variable, and then tries to read another one, here:
message = socketMessage.readUTF();
but the one (first) message you send is already gone.
You have problem in
while (socketMessage.readUTF() != null) {
message = socketMessage.readUTF();
looprunning = false;
}
First call to method readUTF() will block thread and read UTF string from socket, but you discard this value and try read string second time.
If you replace socketMessage.readUTF() != null with looprunning server will log this messages:
VVaiting for connection...
Connection made
socket brain started
entering loop
Message received from UTF: command
loop exited vvith message
no command received
P.S.
Command is not recognized because use compare objects (string is object) with ==, but you must use equals.
public static void StartBrain() throws IOException {
System.out.println("socket brain started");
String BrainMessage = getSocketMessage();
if (BrainMessage.equals("command")) {
System.out.println("Command EXECUTED HAHA");
} else if (BrainMessage.equals("taskschedule")) {
System.out.println("task scheduled");
} else {
System.out.println("no command received");
}
}
Server log:
VVaiting for connection...
Connection made
socket brain started
entering loop
Message received from UTF: command
loop exited vvith message
Command EXECUTED HAHA
Say that I have:
b = true;
while(b){}
Is there any way to continue on after this point? Like some way to modify the value of b without stopping and re running the program?
I want to do this as a simple method to pause the program for an unspecified amount of time, that changes all the time.
You can read the value of b from a data source that is modifiable by the user during runtime.
This can be anything from a database, a network socket, or simply a file.
In this case I would recommend a socket. Below is a very rough, but working, example.
Once you start the program in Eclipse, you need to open a terminal window and telnet localhost 10008.
The accepted commands via the socket are:
<numeric value> = pause the app for that amount of milliseconds
BYE = close the socket
STOP = completely stop the app
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 RuntimePause extends Thread {
protected static boolean appRunning = true;
protected Socket clientSocket;
private long pause = 0;
public static void main(String[] args) throws IOException {
RuntimePause app = new RuntimePause();
app.start();
while (true) {
app.listen();
}
}
public void run() {
while (appRunning) {
System.out.println("App running...");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
if (pause > 0) {
System.out.println("App pausing for " + pause + " ms");
try {
Thread.sleep(pause);
} catch (InterruptedException e) {
}
pause = 0;
}
}
}
public void listen() {
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(10008);
System.out.println("Connection Socket Created");
try {
while (appRunning) {
System.out.println("Waiting for Connection");
new NetworkSocket(serverSocket.accept());
}
} catch (IOException e) {
System.err.println("Accept failed.");
System.exit(1);
}
} catch (IOException e) {
System.err.println("Could not listen on port: 10008.");
System.exit(1);
} finally {
try {
serverSocket.close();
} catch (IOException e) {
System.err.println("Could not close port: 10008.");
System.exit(1);
}
}
}
public class NetworkSocket extends Thread {
public NetworkSocket(Socket clientSoc) {
clientSocket = clientSoc;
start();
}
public void run() {
{
System.out.println("New Communication Thread Started");
try {
PrintWriter out = new PrintWriter(
clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(
new InputStreamReader(clientSocket.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
System.out.println("Received: " + inputLine);
// Client sent a pause command
try {
long pauseCommand = Long.parseLong(inputLine);
pause = pauseCommand;
out.println("OK, pausing for " + inputLine + " ms");
} catch (NumberFormatException e) {
//
}
// Client wishes to terminate connection to socket
if (inputLine.equals("BYE")) {
out.println("OK, bye!");
break;
}
// Client orders the app to stop
if (inputLine.equals("STOP")) {
out.println("OK, stopping!");
System.exit(1);
}
}
out.close();
in.close();
clientSocket.close();
} catch (IOException e) {
System.err.println("Problem with Communication Server");
System.exit(1);
}
}
}
}
}
By the way, this code is not production ready. It simply serves as a example of how you can approach the problem. You want to ensure that the variables are accessed in a thread-safe way.
BOOL b;
- (void)viewDidLoad {
[super viewDidLoad];
//Create a button
UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(100, 100, 100, 100)];
//Which is black
button.backgroundColor = [UIColor blackColor];
//Add it to the view
[self.view addSubview:button];
//When you press the button, do stopPrintingB method
[button addTarget:self action:#selector(stopPrintingB) forControlEvents:UIControlEventTouchUpInside];
b = true;
/*
* This is a GCD means not in the main thread
* If you make while(b) in the main thread
* the program will not do stopPrintingB method until the main thread is free
*/
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
while (b) {
NSLog(#"printing b");
}
});
}
//make b false and stopPrintingB
- (void)stopPrintingB
{
b = false;
}
If you run your program in debug mode you can inject code that will break the loop. In the example posted just change:
b = true;
while(b){}
to:
b = true;
while(b){b=false;}
Then save the file and the loop will be broken.
I'm currently trying to implement the game of Nim using Java, I want to be able to have one player act as the server and another as the player.
I'm fairly new to Java networking and have only had experience using basic TCP/IP where the human client connects to a computer host.
The trouble I'm having is that I need to be able to differentiate between the different players whilst implementing the protocol for the game (The protocol being the logic for the game).
As it stands I can let one player (Client) interact with the Server. All that happens is the Client can play the game but there is no oppostion (The Server merely tracks the state of the game e.g. How many sticks left, valid input etc..).
How would I go about adding a second player to take the place of the host?
Edit:
The Client and Server code has been posted, it is the code I have used and I'm quite comfortable with, the question I am asking is would it be a suitable base to implement a multi-player game or would I need to do something completely different?
My Nim Protocol: (Untested)
public class NimLogic
{
private static final int WAITING = 0;
private static final int EVALUATING = 1;
private static final int ANOTHER = 2;
private int currentState = WAITING;
private int theInput = 0;
private int totalSticks = 10;
String processInput(String input) {
String theOutput = null;
try
{
theInput = Integer.parseInt(input);
}
catch (Exception e)
{
// Ignore conversion error
}
switch (currentState)
{
case WAITING:
theOutput = "Take how many sticks?";
currentState = EVALUATING;
break;
case EVALUATING:
if(theInput == 1 | theInput == 2 | theInput == 3)
{
if (theInput < totalSticks)
{
totalSticks -= theInput;
theOutput = "There are" + totalSticks + " left.";
}
else if (theInput > totalSticks)
{
theOutput = "Error: You cannot take more sticks than that are available";
currentState = EVALUATING;
}
}
if(totalSticks == 1)
{
theOutput = "Game Over! Play again? (Yes = 1, No = 0)...";
currentState = ANOTHER;
}
break;
case ANOTHER:
if (theInput == 1)
{
totalSticks = 10;
currentState = EVALUATING;
theOutput = "Take how many sticks?";
}
else
{
theOutput = "Bye.";
}
}
return theOutput;
}
}
Thanks for all the help!
Edit:
Client
public class Client
{
#SuppressWarnings("static-access")
public static void main(String machine[])
{
Socket kkSocket = null;
PrintStream os = null;
DataInputStream is = null;
try
{
kkSocket = new Socket(machine[0], 4444);
os = new PrintStream(kkSocket.getOutputStream());
is = new DataInputStream(kkSocket.getInputStream());
}
catch(UnknownHostException e)
{
System.err.println("Socket Connect failed on " + machine[0]);
}
catch (IOException e)
{
System.err.println("Streams failed on " + machine[0]);
}
if (kkSocket != null && os != null && is != null )
{
try
{
String fromServer, fromClient;
while((fromServer = is.readLine()) != null && !fromServer.equals("Bye."))
{
fromClient = JOptionPane.showInputDialog(fromServer);
os.println(fromClient);
}
JOptionPane.showMessageDialog(null, "Goodbye, keep smiling.");
os.close();
is.close();
kkSocket.close();
}
catch (UnknownHostException e)
{
System.err.println("Can't connect to " + machine[0] + e);
}
catch (IOException e)
{
e.printStackTrace();
System.err.println("I/O failed on " +machine[0]);
}
}
}
}
Server
public class Server
{
public static void main(String arg[])
{
ServerSocket serverSocket = null;
try
{
serverSocket = new ServerSocket(4444);
}
catch (IOException e)
{
System.err.println("Can't listen on 4444 -> " + e);
System.exit(1);
}
Socket clientSocket = null;
try // allow the client to connect
{
clientSocket = serverSocket.accept();
}
catch (IOException e)
{
System.err.println("Failed accept on 4444 -> " + e);
System.exit(1);
}
try
{
DataInputStream is =
new DataInputStream(new BufferedInputStream
(clientSocket.getInputStream()));
PrintStream os =
new PrintStream(new BufferedOutputStream
(clientSocket.getOutputStream(), 1024), false);
GuessState kks = new GuessState();
String inputLine, outputLine;
outputLine = kks.processInput(null);
os.println(outputLine);
os.flush();
while((inputLine = is.readLine()) != null
&& !outputLine.equals("Bye."))
{
outputLine = kks.processInput(inputLine);
os.println(outputLine);
os.flush();
}
os.close();
is.close();
clientSocket.close();
serverSocket.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
I'm not quite sure if I'm answering your question here, so apologies if I'm not. Also, it's been a little while since I did any Java networking code, so there might be a few wrinkles here which hopefully others can sort out.
The following is a bit of a brain dump of the changes I'd probably make, for better or worse...
Rework the networking code to accept multiple connections. Normally you'd do this by handing off the socket returned by ServerSocket.accept to a thread to process. If you were dealing with a lot of connections, you could do it using NIO instead, but that's probably too far to fast for now.
Separate the game state from the client conversation code. To keep things simple, embed the client conversation code in the thread object. The game state needs to be in an object that's shared between all the threads servicing the socket.
I'd recommend making the game state a proper 'domain object' rather than having it parsing strings etc. It should have operations like 'take(clientID, int)' rather than 'processInput'.
Consider using the observer pattern to distribute events from the domain object to the socket threads. Examples of events might be 'turnTaken' or 'gameComplete'.
Embed the notion of 'turns' into the game object, and have the server broadcast an event to the socket threads announcing whose turn it is.
Hope that gives you a starter for ten?
The server/client aspect should have no bearing on the communication of the two players. You should be able to spawn two instances of the Nim game, one that listen for an incoming connection on some port(Server), and one that connects to it (Client). Once the connection is established, you can pass Objects between the two instances over your connection that represent game information. Each instance of your Nim game is responsible for parsing that game data and running the Nim logic on it.
In essence, each instance of the game can run as a server or a client. Here's some code I wrote for Chess that should be applicable. Read through it. Elsewhere I instance a Server or Client and store it in a reference of type NetworkIdenitity.
private abstract class NetworkEntity
extends Thread {
ObjectOutputStream outputStream;
ObjectInputStream inputStream;
Socket connectionHandle;
Object messageToSend;
Object receivedMessage;
public NetworkEntity(final String name) {
super(name);
}
#Override
public abstract void run();
public void getStreams()
throws IOException {
this.outputStream = new ObjectOutputStream(this.connectionHandle.getOutputStream());
this.outputStream.flush();
this.inputStream = new ObjectInputStream(this.connectionHandle.getInputStream());
}
public void closeConnection() {
try {
if (this.outputStream != null) {
this.outputStream.close();
}
if (this.inputStream != null) {
this.inputStream.close();
}
if (this.connectionHandle != null) {
this.connectionHandle.close();
chatPanel.writeToDisplay("Connection closed with "
+ this.connectionHandle.getInetAddress().getHostName());
}
}
catch (final IOException e) {
JOptionPane.showMessageDialog(thisFrame, "Problems experienced when closing connection",
"Notification", JOptionPane.ERROR_MESSAGE);
}
}
public void processIncomingData()
throws IOException {
do {
try {
this.receivedMessage = this.inputStream.readObject();
}
catch (final ClassNotFoundException e) {
JOptionPane.showMessageDialog(thisFrame, "read() error: message from "
+ this.connectionHandle.getInetAddress().getHostName() + " not received", "Notification",
JOptionPane.ERROR_MESSAGE);
}
if (this.receivedMessage instanceof Move) {
final Move m = (Move) this.receivedMessage;
System.out.println(getName() + " got move" + m);
requestMove(Table.this.chessBoard, Table.this.currentPlayer, Table.this.currentOpponent, m, false);
repaint();
}
else if (this.receivedMessage instanceof Board) {
final Board b = (Board) this.receivedMessage;
System.out.println(getName() + " received this board:");
b.printCurrentBoardState();
// System.out.println("local copy looked like this: " );
// chessBoard.printCurrentBoardState();
// chessBoard.setGameBoard(b.getGameBoard());
// switchCurrentPlayer();
// chessBoard.updateBoardState(currentPlayer,
// currentOpponent);
repaint();
}
else if (this.receivedMessage instanceof String) {
chatPanel.writeToDisplay((String) this.receivedMessage);
}
} while (/* !message.equals("SERVER>>> TERMINATE") */true);
}
public void sendData(final Object obj_to_send) {
try {
this.outputStream.writeObject(obj_to_send);
this.outputStream.flush();
}
catch (final IOException e) {
}
}
}
private final class Client
extends NetworkEntity {
private final String hostName;
private final int serverPort;
public Client(final String host, final int port) {
super("CLIENT");
this.hostName = host;
this.serverPort = port;
}
#Override
public void run() {
try {
connectToServer();
getStreams();
processIncomingData();
}
catch (final EOFException eof) {
}
catch (final IOException ioe) {
}
catch (final NullPointerException npe) {
}
finally {
closeConnection();
}
}
private void connectToServer()
throws IOException {
try {
this.connectionHandle = new Socket(InetAddress.getByName(this.hostName), this.serverPort);
connectionEstablished = true;
chatPanel.writeToDisplay("Successfully connected to "
+ this.connectionHandle.getInetAddress().getHostName());
}
catch (final IOException e) {
chatPanel.writeToDisplay("Failed to connect to: " + this.hostName);
}
}
}
private final class Server
extends NetworkEntity {
private ServerSocket server;
private final int listenPort;
public Server(final int listen_port) {
super("SERVER");
this.listenPort = listen_port;
}
#Override
public void run() {
try {
this.server = new ServerSocket(this.listenPort, 1);
chatPanel.writeToDisplay("Listening on port " + this.listenPort);
try {
waitForConnection();
getStreams();
processIncomingData();
}
catch (final EOFException eof) {
// System.out.println(getName() + "exception: " +eof);
// eof.printStackTrace();
}
catch (final IOException ioe) {
// System.out.println(getName() + "exception: " +ioe);
// ioe.printStackTrace();
}
finally {
closeConnection();
}
}
catch (final IOException e) {
JOptionPane.showMessageDialog(thisFrame, "Network Error: " + e, "Notification",
JOptionPane.ERROR_MESSAGE);
}
}
private void waitForConnection()
throws IOException {
this.connectionHandle = this.server.accept();
connectionEstablished = true;
chatPanel.writeToDisplay("Connection received from:" + this.connectionHandle.getInetAddress().getHostName());
}
#Override
public void closeConnection() {
super.closeConnection();
try {
this.server.close();
}
catch (final IOException e) {
chatPanel.writeToDisplay(getName() + "failed to disconnect from the network");
}
}