So I don't know who to go about creating a multithreaded server. I have client and server working fine together but can't introduce multiple clients properly. Here is my Server code:
package dod;
import java.net.*;
import java.io.*;
import dod.game.GameLogic;
public class Server{
Server(GameLogic game, int port) throws IOException{
ServerSocket ss = null;
Socket sock = null;
try{
ss = new ServerSocket(4444);//port no.
while(true){
try{
sock = ss.accept();
ClientThread thread = new ClientThread(game, sock);
System.out.println("Adding new player...");
thread.run();
}catch(final Exception e) {
System.err.println(e.getMessage());
System.exit(1);
}
}
}catch(Exception d){
System.out.println(d);
}finally{
if(ss!=null){
ss.close();
}
}
}
}
Here is my thread class:
package dod;
import java.io.*;
import java.net.Socket;
import dod.game.GameLogic;
import dod.game.PlayerListener;
public class ClientThread extends CommandLineUser implements PlayerListener, Runnable{
DataInputStream in;
PrintStream out;
// The game which the command line user will operate on.
// This is private to enforce the use of "processCommand".
ClientThread(GameLogic game, Socket sock) {
super(game);
try{
in = new DataInputStream(sock.getInputStream());
out = new PrintStream(sock.getOutputStream());
}catch(IOException ioe){
System.out.println(ioe);
}
game.addPlayer(this);
}
/**
* Constantly asks the user for new commands
*/
public void run() {
System.out.println("Added new human player.");
// Keep listening forever
while(true){
try{
// Try to grab a command from the command line
final String command = in.readLine();;
// Test for EOF (ctrl-D)
if(command == null){
System.exit(0);
}
processCommand(command);
}catch(final RuntimeException e){
System.err.println(e.toString());
System.exit(1);
} catch (final IOException e) {
System.err.println(e.toString());
System.exit(1);
}
}
}
/**
* Outputs a message to the player
*
* #param message
* the message to send to the player.
*/
public void outputMessage(String message) {
out.print(message);
}
}
Not asking for new code as such, just need pointers as to what I need to do have multiple client connection at the same time! Thanks to anyone who helps out!
To start, add new Thread(clientThread) in the server and call start() on it - as is everything's happening on the same thread.
public class Server{
Server(GameLogic game, int port) throws IOException{
ServerSocket ss = null;
Socket sock = null;
try{
ss = new ServerSocket(4444);//port no.
while(true){
try{
sock = ss.accept();
ClientThread thread = new ClientThread(game, sock);
System.out.println("Adding new player...");
thread.start(); //you have to use start instead of run method to create multi thread application.
}catch(final Exception e) {
System.err.println(e.getMessage());
System.exit(1);
}
}
}catch(Exception d){
System.out.println(d);
}finally{
if(ss!=null){
ss.close();
}
}
}
}
You have to use start instead of run method to create multi thread application.
If you want to send messages about new connections you have to hold sock in a list and when a new connection accepted send message to all socket object in list. (server broadcasts to all connected sockets)
I hope it helps.
Related
I'm writing a client/server app in java. Is this code correct to check if some socket of a client is already connected to my server? I'm quite new and it is my first app with this characteristics so don't kill me...
package ServerCommunication;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class MultiServer {
public void openSocket() throws IOException {
ServerSocket serverSocket = null;
boolean listening = true;
MultiServerThread w=null;
try {
serverSocket = new ServerSocket(1633);
System.out.println("Waiting on 1633.");
} catch (IOException e) {
System.err.println("Could not listen on port: 1633.");
System.exit(-1);
}
while (listening) {
System.out.println("Hearing");
Socket mysocket=serverSocket.accept();
if(mysocket.isConnected())
System.out.println("Already connected");
else{
System.out.println("Need to create one");
w = new MultiServerThread(mysocket);
Thread t = new Thread(w);
t.start();
}
}
serverSocket.close();
System.out.println("Multiserver closed");
}
}
No.
while (listening) {
System.out.println("Hearing");
Socket mysocket=serverSocket.accept();
The result of executing this line of code is either an IOException or a Socket connected to the client.
if(mysocket.isConnected())
Pointless. It's connected. Remove.
System.out.println("Already connected");
Of course it's connected. That's what accept() is for. Remove.
else{
Unreachable. Remove.
System.out.println("Need to create one");
No you don't. Remove.
w = new MultiServerThread(mysocket);
Thread t = new Thread(w);
t.start();
This is all pointless. Remove.
I just started using Sockets, and for my current project I need to be able to control my program from a client, however if my project-partner wants use his client at the same time, the server doesn't send him the "You are connected" message as shown in the connection class. So I assume the server doesn't accept mutiple clients at the same time. I have tried using a Thread of the class Connection, but that also doesn't send the message "You are connected" to the second Client. What am I doing wrong here?
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class Listener extends Thread{
private ServerSocket server;
private int PORT;
public boolean running;
public Listener(int port){
try{
this.PORT = port;
this.server = new ServerSocket(PORT,10);
}catch (IOException e) {
System.out.println("Could not create serverSocket...");
}
}
#Override
public void run() {
this.running = true;
try{
waitForConnection();
}catch(IOException e){
System.out.println("Could not accept connection request..");
run();
}
}
public void dispose(){
try{
System.out.println("DISPOSE");
running = false;
server.close();
} catch (IOException i) {
System.out.println("Could not close ServerSocket");
}
}
private void waitForConnection() throws IOException{
while(running){
System.out.println("Waiting for connection");
Socket client = server.accept();
Runnable connection = new Connection(client);
new Thread(connection).start();
}
}
}
This is the Thread I'm using to have multiple users connect at the same time:
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
public class Connection extends Thread {
Socket connection;
private ObjectOutputStream output;
private ObjectInputStream input;
private boolean running;
public Connection(Socket connect){
this.connection = connect;
try {
setupStreams();
whileListening();
} catch (IOException e) {
System.out.println("could not connect to: "+ connection.getInetAddress().getHostName());
}
}
public void dispose(){
try{
output.close();
input.close();
connection.close();
running = false;
}catch(IOException ioException){
ioException.printStackTrace();
}
}
private void whileListening(){
String message = "You are connected! ";
sendMessage(message);
do{
try{
message = (String) input.readObject();
checkMessage(message);
}catch(ClassNotFoundException classNotFoundException){
sendMessage("tf did you send? ");
}catch (IOException e) {
dispose();
run();
}
}while(!message.equals("Client - END") && running == true);
}
private void setupStreams() throws IOException{
output = new ObjectOutputStream(connection.getOutputStream());
output.flush();
input = new ObjectInputStream(connection.getInputStream());
}
private void sendMessage(String message){
try {
output.writeObject("Server - " + message+"\n");
output.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
private void checkMessage(String text){
//check the message
}
}
EDIT: Addittional information
Before the first client connects, the server console says "Waiting for connection", then when the first client connects, the client console says "You are connected" and, when a second client connects, the console is black, when I close the first client, the second client console says "You are connected" and the server console says "Waiting for connection", then if I close the second client aswell, the server console says "Waiting for connection" again.
In your constructor of the public class Connection extends Thread you do this whileListening()stuff, so your constructor never ends, you need to override the run() function and do that there
#Override
public void run() {
while(true) {
try {
whileListening();
} catch(Exception e) {}
}
}
like so, it should do the trick.
I think you must accept first, after that you start the thread.
For example, let's suppose something like this
in your main class, you get the ServerSocketFactory and then the ServerSocket.
then, inside an (endless) loop, you wait for a new Socket returned by the ServerSocket.accept()
Only after that, you start your thread
Here's an example from a SSLServerSocket, which is pretty much the same logic (consider it a pseudo-code)
SSLContext sc = SSLContext.getInstance("TLS");
(...)
SSLServerSocketFactory ssf = sc.getServerSocketFactory();
SSLServerSocket s = (SSLServerSocket) ssf.createServerSocket(portNumber);
while (listening) {
SSLSocket c = (SSLSocket) s.accept();
log.info("Serving");
new SimpleSSLServerSocketThread(c).start();
}
I'm new in Java Sockets, I have seen so many examples but I can't understand how to pass an argument from server to client and vice versa. My destination is to pass an Object that's why I'm using Object I/O Stream.
I have to classes Server and Player.
public class Server extends Thread{
public static final int TEST = 165;
ServerSocket serverSocket;
InetAddress address;
Player playerWhite;
public Server() {
start();
}
#Override
public void run() {
try
{
address = InetAddress.getLocalHost();
serverSocket = new ServerSocket(6000);
playerWhite = new Player();
System.out.println("server waits for players");
playerWhite.socket = serverSocket.accept();
playerWhite.start();
sendTestMessage(playerWhite);
}
catch (IOException ex)
{
Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void sendTestMessage(Player player) throws IOException
{
ObjectOutputStream testToClient = new ObjectOutputStream(player.socket.getOutputStream());
testToClient.write(TEST);
testToClient.flush();
}
And the Player class:
public class Player extends Thread {
Socket socket;
Player() throws IOException
{
socket = new Socket(InetAddress.getLocalHost(), 6000);
}
#Override
public void run() {
try {
listenTestStream();
}
catch (IOException | ClassNotFoundException ex)
{
Logger.getLogger(CheckerPlayer.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void listenTestStream() throws IOException, ClassNotFoundException
{
ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
int message = ois.readInt();
//To test
System.out.println("Server listened: " + message);
}
I execute it as create a Server object in the other class.
When I have testing this application I saw that sometimes client is faster than Server. Is it possible to make him "wait" for server response?
Thanks for your response.
EDIT 1: PROBLEM SOLUTION:
From outside we should create:
Player player = new Player(); // (class player extends from Thread)
player.start();
and delete the Player variable - is not necessary, we need only Socket so:
Server:
Socket playerWhiteSocket
public void run() {
try
{
serverSocket = new ServerSocket(PORT);
playerWhiteSocket = serverSocket.accept();
sendMessage(playerWhiteSocket, "Hello");
}
catch(IOException | ClassNotFoundException ex)
{}
public void sendMessage(Socket socket, String message) throws IOException
{
ObjectOutputStream testToClient = new ObjectOutputStream(socket.getOutputStream());
testToClient.writeObject(message);
testToClient.flush();
}
In Player class we need get method:
public String receiveMessage() throws IOException, ClassNotFoundException
{
//socket is a variable get from Player class socket = new Socket("severHost", PORT);
ObjectInputStream messageFromServer = new ObjectInputStream(socket.getInputStream());
String message = (String) messageFromServer.readObject();
return message;
}
I would recomment doing this public void start(){
try {
ServerSocket = new ServerSocket(this.port,10,this.localAddress);
// set timeout if you want
//this.clientServerSocket.setSoTimeout(timeout);
// infinity loop
while(true)
{
//wait for a client connection
Socket socket = ServerSocket.accept();
// start thread for every new client
Thread t = new Thread(new AcceptClients(this.socket));
t.start();
System.out.println(L"new client connected");
// call garbage collector and hope for the best
System.gc();
}
} catch (IOException e) {
System.out.println("IO Error");
e.printStackTrace();
}
}
and then in another class
public class AcceptClients implements Runnable{
// socket
private Socket socket;
public AcceptClients (Socket socket){
this.socket = socket;
}
#Override
public void run() {
// what happens if a client connect
}
}
I always use this and it works fine
Suggested changes.
Create ServerSocket only once. If you have done it, you won't get "Address already in use" error
After creating Server Socket, you thread should be in while (true) loop to accept connection from client.
Once you create a client socket, pass that socket to thread.
Now Player is used to send communication from server to client socket. So You need one more class like PlayerClient which create a socket to Server IP and Port. Now PlayerClient should create one more thread to handle IO operations like you have done from server. In this case, creating a socket is not in while loop from client side. It create a socket to server once. Now you can run this PlayerClient program from multiple machines.
If you are just sending just primitive type, use DataOutputStream & DataInputStream instead of ObjectStreams
This code will become like this
try
{
address = InetAddress.getLocalHost();
serverSocket = new ServerSocket(6000);
System.out.println("server waits for players");
while ( true){
Socket socket = serverSocket.accept();
Player playerWhite = new Player(socket);
sendTestMessage(socket);// Move this method to Player thread and change the signature of this method accordingly to accept a socket
}
}
catch (IOException ex)
{
Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
}
Player.java
Player(Socket socket) throws IOException
{
this.socket = socket;
start();
}
Have a look at this chat example for better understanding.
Yep it is.
It should work if you put it in a endlees loop like that:
try
{
while(true){
address = InetAddress.getLocalHost();
serverSocket = new ServerSocket(6000);
playerWhite = new Player();
System.out.println("server waits for players");
playerWhite.socket = serverSocket.accept();
playerWhite.start();
sendTestMessage(playerWhite);
}
}
catch (IOException ex)
{
Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
}
But I would not recommend to put this in a thread. Instead I would put the connection of a new client in a thread, so multiple clients can connect to the server
I have the following code for sending data over a socket:
socketclient.java
import java.io.*;
import java.net.Socket;
import java.net.UnknownHostException;
public class SocketClient
implements Runnable
{
private Socket socket;
private String ServerIP = "192.168.0.11";
private static final int ServerPort = 7000;
#Override
public void run()
{
try
{
socket = new Socket(ServerIP, ServerPort);
}
catch(Exception e)
{
System.out.print("Whoops! It didn't work on ip" + ServerIP + "!:");
System.out.print(e.getLocalizedMessage());
System.out.print("\n");
}
}
public void Send(String s)
{
try
{
Thread.sleep(10);
OutputStream out = socket.getOutputStream(); //Starts the output stream
PrintWriter output = new PrintWriter(out);
output.println(s); //sends the data over the socket
output.flush(); //flushes the outputwriter
output.close(); //closes the outputwriter
out.close(); //closes the outputstream
}
catch (UnknownHostException e) {
System.out.print(e.toString());
} catch (IOException e) {
System.out.print(e.toString());
}catch (Exception e) {
System.out.print(e.toString());
}
}
}
When i dont have the sleep in the send function the server output looks like this (i have it set to print the 'conn' and 'addr' of every connection), the server is coded in python
Connected with 192.168.0.11:52578
in client thread
Connected with 192.168.0.11:52579
in client thread
Connected with 192.168.0.11:52609
in client thread
and the server connection data recieveing/main connection thread is this:
def clientthread(conn):
#Sending message to connected client
#Receiving from client
data = conn.recv(4096)
print data
#came out of loop
conn.close()
My goal for the server is to open/close sockets on the client-side everytime i want to send data because i want each reciever to create its own connections using a socket class i created.
What is the reason for having to add a thread.sleep() before sending a string over a TCP socket in java?
Also, this is how i use my Socketclient class:
SMSClient = new SocketClient();
Thread thread = new Thread(SMSClient);
thread.start();
SMSClient.Send(smsData);
When you instantiate a new SocketClient object you are not running the new thread. You should call your Send(String s) method just after socket = new Socket(ServerIP, ServerPort); from inside the run method.
To know the current thread in your running code put some log like the following: Log.d("label", "thread id: "+android.os.Process.myTid()). Try for example to evaluate the current thread inside run method, and inside the Send(String s) method when you call this latter as you are doing and after having moved the call to the method inside the run.
I suggest to use IntentService for your purpose since, when needed, you can managed easily the socket connection and transmission in a separate thread.
When the thread.start() call returns the thread may not have executed yet. And then you are sending already your first request. You may wait with sleep after thread.start() that is better (while sleeping in the main thread the connection thread has a chance to run) - but still not best practice. Here is my working code ( I added a main function to the SocketClient ):
import java.io.*;
import java.net.Socket;
import java.net.UnknownHostException;
public class SocketClient
implements Runnable
{
private Socket socket;
private String ServerIP = "127.0.0.1";
private static final int ServerPort = 7000;
#Override
public void run()
{
try
{
socket = new Socket(ServerIP, ServerPort);
}
catch(Exception e)
{
System.out.print("Whoops! It didn't work on ip" + ServerIP + "!:");
System.out.print(e.getLocalizedMessage());
System.out.print("\n");
}
}
public void Send(String s)
{
try
{
OutputStream out = socket.getOutputStream(); //Starts the output stream
PrintWriter output = new PrintWriter(out);
output.println(s); //sends the data over the socket
output.flush(); //flushes the outputwriter
output.close(); //closes the outputwriter
out.close(); //closes the outputstream
}
catch (UnknownHostException e) {
System.out.print(e.toString());
} catch (IOException e) {
System.out.print(e.toString());
}catch (Exception e) {
System.out.print(e.toString());
}
}
static public void main(String[] args)
{
SocketClient socketClient = new SocketClient();
Thread thread = new Thread(socketClient);
thread.start();
try
{
Thread.sleep(19);
}
catch(Exception e) {}
socketClient.Send("hallo");
}
}
I've got a simple client and server that I've written to teach myself a bit of networking. The way it's set up is I've got a main server class which will deal with creating/destroying sockets, and the ConnectionThread class that represents each connection (each of which is given its own thread). The client is super simple.
The problem lies in creating the input/output streams in the ConnectionThread class. I'm not sure exactly what the problem is, but it crashes when the simple test client tries to connect, giving me this:
~~MMO Server Alpha .1~~
Constructed Server
Server Initialized, preparing to start...
Server preparing to check if it should be listening...
Server should be listening, continuing as planned.
ServerSocket passed to ConnectionThread: ServerSocket[addr=0.0.0.0/0.0.0.0,localport=6969]
Constructing ConnectionThread.
Socket[addr=/10.0.1.10,port=55332,localport=6969]
ConnectionThread constructed.
Exception in thread "main" java.lang.NullPointerException
at ConnectionThread.init(ConnectionThread.java:65)
at Server.listen(Server.java:98)
at Server.start(Server.java:62)
at Server.main(Server.java:122)
ConnectionThread added to queue.
Establishing in and out streams:
null
Here are the classes (amended for brevity):
public class Server {
int PORT;
boolean shouldListen;
ArrayList<ConnectionThread> connections = new ArrayList<ConnectionThread>();
ServerSocket serverSocket;
public Server() {
try {
PORT = 6969;
shouldListen = true;
serverSocket = new ServerSocket(PORT);
}
catch (IOException e) {
System.out.println("Error in server constructor.");
System.exit(1);
}
}
public void start() {
System.out.println("Server preparing to check if it should be listening...");
listen();
System.out.println("Server finished listening.");
}
public void listen() {
while (shouldListen) {
ConnectionThread conn = null;
System.out.println("Server should be listening, continuing as planned.");
try {
conn = new ConnectionThread(serverSocket);
}
catch (Exception e) {
System.out.println("____Error constructing ConnectionThread. Could there be another instance of the server running?");
System.exit(1);
}
System.out.println("ConnectionThread constructed.");
connections.add(conn);
System.out.println("ConnectionThread added to queue.");
conn.init();
System.out.println("Finished ConnectionThread initialization, verifying...");
if (conn.isInitialized) {
System.out.println("ConnectionThread Initialized, preparing to start new thread.");
(new Thread(conn)).start();
}
}
}
public static void main(String[] args) {
System.out.println("~~MMO Server Alpha .1~~");
Server server = new Server();
System.out.println("Constructed Server");
server.init();
System.out.println("Server Initialized, preparing to start...");
server.start();
}
}
Here's the ConnectionThread class:
public class ConnectionThread implements Runnable {
boolean shouldBeListening = true;
boolean isThereAnUnsentOutgoingMessage = false;
String outgoingMessage = "OUTGOING UNINITIALIZED";
boolean IsThereAnUnsentIncomingMessage = false;
String incomingMessage = "INCOMING UNITIALIZED";
boolean isInitialized = false;
PrintWriter out;
BufferedReader in;
String currentInputMessage = "Test Input Message from the Server ConnectionThread";
String previousInputMessage = null;
Socket socket;
public ConnectionThread(ServerSocket s) {
System.out.println("ServerSocket passed to ConnectionThread: " + s);
/*
* The purpose of the constructor is to establish a socket
* as soon as possible. All transmissions/logic/anything else
* should happen in init() and/or run().
*/
System.out.println("Constructing ConnectionThread.");
try {
Socket socket = s.accept();
System.out.println(socket);
}
catch (IOException e) {
System.out.println("Error in ConnectionThread constructor");
System.exit(1);
}
}
public void init() {
/*
* Everything should be set up here before run is called.
* Once init is finished, run() should be set to begin work.
* This is to ensure each packet is efficiently processed.
*/
try {
System.out.println("Establishing in and out streams:");
System.out.println(socket);
out = new PrintWriter(socket.getOutputStream(), true);
System.out.println("ConnectionThread: Output Stream (PrintWriter) Established");
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
System.out.println("ConnectionThread: InputStream (BufferedReader) Established");
}
catch (IOException e) {
System.out.println("Error in ConnectionThread method Init.");
System.exit(1);
}
isInitialized = true;
}
And optionally, here's the test client:
public class TestClient {
static PrintWriter out;
BufferedReader in;
public final int PORT = 6969;
Socket socket = null;
InetAddress host = null;
public TestClient() {
out = null;
in = null;
socket = null;
host = null;
}
public void connectToServer() {
System.out.println("Connecting to server...");
try {
host = InetAddress.getLocalHost();
socket = new Socket(host.getHostName(), PORT);
}
catch (Exception e) {
System.out.println("Error establishing host/socket");
System.exit(1);
}
try {
System.out.println("Establishing I/O Streams");
out = new PrintWriter(socket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
}
catch (Exception e) {
System.out.println("Error establishing in/out streams");
System.exit(1);
}
}
public static void main(String[] args) {
System.out.println("~~TestClient Alpha .1~~");
TestClient c = new TestClient();
c.connectToServer();
System.out.println("Should be connected to server. Sending test message...");
while (true) {
System.out.println("here");
out.println("Hello there");
}
}
}
The 'socket' variable in the constructor of ConnectionThread shouldn't be local. It is shadowing the member variable.
It is customary to call accept() in the listen() loop, and pass the accepted socket to the ConnectionThread.
As EJP said, in your ConnectionThread constructor you think that you are assigning the value to the socket field, however you are actually assigning the value to the socket method variable, thus the socket field remains null, and in init() you see socket as null.
In addition to EJP answer: you did not provide ConnectionThread.run() method, but I assume you are going to use fields in, out and socket in your run() method. Since these fields are not marked as volatile or final, depending on your luck and number of core on your computer, you may also get NullPointerException at run() method.
This is because new variable value may be not propagated between caches and new thread will not see value of changed.
Explanation of this possible problem is here - The code example which can prove "volatile" declare should be used