im making a server for an application, and I made a thread for accepting user's.
but it seems that it doesn't come to my overrided method run()
it doesn't give me an error or such it just doesn't run.
Here is the code:
This is the Client listener
package org.walking.server.listener;
import java.io.IOException;
import java.net.ServerSocket;
import javax.swing.SwingWorker;
/*
* Walking client listener!
*/
public class WalkingCL {
private SwingWorker work;
ServerSocket server;
public boolean listening = true;
public void acceptclient(){
try {
System.out.println("Created server socket");
server = new ServerSocket(4444);
} catch (IOException e) {
System.err.println("Error while creating ServerSocket on port 4444");
e.printStackTrace();
}
work = new SwingWorker<Object,Void>(){
public Object doInBackground(){
while(listening){
try {
new WalkingCLT(server.accept()).start();
} catch (IOException e) {
System.err.println("Error while making thread!");
e.printStackTrace();
}
}
return listening;
}
};
}
}
Here is the client listener thread:
package org.walking.server.listener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
/*
* Walking Client listener Thread!
*/
public class WalkingCLT extends Thread {
private Socket client;
public WalkingCLT(Socket client){
super("Walking client listener thread!");
this.client = client;
}
#Override
public void run(){
System.out.println("HELLO?");
try {
System.out.println("User:" + client.getInetAddress() + "connected!");
PrintWriter out = new PrintWriter(client.getOutputStream(),true);
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
out.println("HELLO?");
out.flush();
out.close();
in.close();
client.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
I've put some println statments to see if it comes to that but I only see this:
Server stacktrace:
Created server socket
Client stacktrace:
Panel Created!
Your connected!
Hope you can help me.
Thanks!
You are only creating an instance of the SwingWorker task. You are missing a call to work.execute() or work.doInBackground() by some helper class. You need to look at the ExecutorService and how to use it to submit and execute SwingWorker tasks. There is also a small code snippet in the Future documentation.
Related
I have a client-server app.
It opens a socket on client side, then I input data to send, it's also sent to other clients, but then the socket is closed. Why? I have tried many different approaches, like shifting din and dout to thread itself, adding some handlers, etc. But no progress yet.
I saw some other problems like this, but the solutions there are not applicable to my problem (I am not so experienced in sockets). Would like a solution to my specific problem.
Errors:
java.net.SocketException: Socket is closed
at java.base/java.net.Socket.getInputStream(Socket.java:927)
at com.uniqueapps.network.ClientThread.lambda$run$1(ClientThread.java:23)
at java.base/java.lang.Thread.run(Thread.java:833)
java.net.SocketException: Socket is closed
at java.base/java.net.Socket.getOutputStream(Socket.java:998)
at com.uniqueapps.network.ClientThread.lambda$run$0(ClientThread.java:28)
at java.base/java.lang.Thread.run(Thread.java:833)
Exception in thread "Thread-2" java.util.ConcurrentModificationException
at java.base/java.util.ArrayList$Itr.checkForComodification(ArrayList.java:1013)
at java.base/java.util.ArrayList$Itr.next(ArrayList.java:967)
at com.uniqueapps.network.ClientThread.lambda$run$0(ClientThread.java:27)
at java.base/java.lang.Thread.run(Thread.java:833)
Server.java codes:
package com.uniqueapps.network;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.ArrayList;
public class Server {
final static int PORT = 5555;
static ServerSocket serverSocket;
static ArrayList<ClientThread> clients = new ArrayList<>();
public static void main(String[] args) {
try {
serverSocket = new ServerSocket(PORT);
new Thread(() -> {
while (true) {
try {
Socket clientSocket = serverSocket.accept();
ClientThread client = new ClientThread(clientSocket);
client.run();
clients.add(client);
System.out.println("New client joined: " + client.socket.getLocalPort());
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
ClientThread.java codes:
package com.uniqueapps.network;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.IOException;
import java.net.Socket;
import java.net.SocketException;
public class ClientThread implements Runnable {
Socket socket;
public ClientThread(Socket socket) {
this.socket = socket;
}
#Override
public void run() {
new Thread(() -> {
boolean run = true;
while (run) {
try (DataInputStream din = new DataInputStream(socket.getInputStream())) {
String text = din.readUTF();
if (!text.equals("")) {
new Thread(() -> {
for (ClientThread clientThread : Server.clients) {
try (DataOutputStream dout = new DataOutputStream(clientThread.socket.getOutputStream())) {
dout.writeUTF(text);
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
} catch (EOFException ignored) {
} catch (SocketException e) {
e.printStackTrace();
Server.clients.remove(this);
run = false;
System.out.println("Client left: " + socket.getLocalPort());
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
}
Client.java codes:
package com.uniqueapps.network;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.IOException;
import java.net.Socket;
import java.util.Scanner;
public class Client {
public static void main(String[] args) {
try {
Socket socket = new Socket("localhost", 5555);
socket.setKeepAlive(true);
new Thread(() -> {
try {
DataOutputStream dout = new DataOutputStream(socket.getOutputStream());
Scanner scn = new Scanner(System.in);
while (true) {
String text = scn.nextLine();
if (!text.equals("")) {
try {
dout.writeUTF(text);
} catch (IOException e) {
e.printStackTrace();
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
}).start();
new Thread(() -> {
try {
DataInputStream din = new DataInputStream(socket.getInputStream());
while (true) {
try {
String text = din.readUTF();
if (!text.equals("")) {
System.out.println(text);
}
} catch (EOFException ignored) {
} catch (IOException e) {
e.printStackTrace();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}).start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Edit:
Thanks to Michael Lee, i understood the problem i have been trying to understand for weeks. I remade the code, but i am stuck a place.
I got to know that the .run(); method of "runnable" halts the current thread, but .start(); of "thread" doesn't. So i removed threads from all places, except one. This place is still getting the "Socket closed" error (If i keep runnable here, then the thread is halted, and the message not relayed to other clients). How can i overcome this?
Server.java:
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.ArrayList;
public class Server {
final static int PORT = 8686;
static ServerSocket serverSocket;
static ArrayList<ClientThread> clients = new ArrayList<>();
public static void main(String[] args) {
try {
serverSocket = new ServerSocket(PORT);
System.out.println("Server ready! Running on port " + PORT);
while (true) {
try {
Socket clientSocket = serverSocket.accept();
System.out.println("New client joined: " + clientSocket.getPort());
ClientThread client = new ClientThread(clientSocket);
System.out.println("Created thread for client.");
clients.add(client);
System.out.println("Added client to list.");
} catch (IOException e) {
e.printStackTrace();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
ClientThread.java:
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.IOException;
import java.net.Socket;
import java.net.SocketException;
public class ClientThread extends Thread {
Socket socket;
public ClientThread(Socket socket) {
this.socket = socket;
this.start();
System.out.println("Started thread for client.");
}
#Override
public void run() {
try {
boolean run = true;
DataInputStream din = new DataInputStream(socket.getInputStream());
while (run) {
try {
String text = din.readUTF();
if (!text.equals("")) {
for (ClientThread clientThread : Server.clients) {
try (DataOutputStream dout = new DataOutputStream(clientThread.socket.getOutputStream())) {
dout.writeUTF(text);
} catch (IOException e) {
e.printStackTrace();
}
}
}
} catch (EOFException ignored) {
} catch (SocketException e) {
e.printStackTrace();
Server.clients.remove(this);
run = false;
System.out.println("Client left: " + socket.getPort());
} catch (IOException e) {
e.printStackTrace();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Client.java:
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.IOException;
import java.net.Socket;
import java.net.SocketException;
public class ClientThread extends Thread {
Socket socket;
public ClientThread(Socket socket) {
this.socket = socket;
this.start();
System.out.println("Started thread for client.");
}
#Override
public void run() {
try {
boolean run = true;
DataInputStream din = new DataInputStream(socket.getInputStream());
while (run) {
try {
String text = din.readUTF();
if (!text.equals("")) {
for (ClientThread clientThread : Server.clients) {
try (DataOutputStream dout = new DataOutputStream(clientThread.socket.getOutputStream())) {
dout.writeUTF(text);
} catch (IOException e) {
e.printStackTrace();
}
}
}
} catch (EOFException ignored) {
} catch (SocketException e) {
e.printStackTrace();
Server.clients.remove(this);
run = false;
System.out.println("Client left: " + socket.getPort());
} catch (IOException e) {
e.printStackTrace();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
In your ClientThread, after din.readUTF(); if (!text.equals("")) { ..., you should directly start processing the incoming data in current thread, rather than initializing a new thread to handle them.
Because in you current thread, the one holding the connected socket, probably closed before the new thread has not even started up. As Java Docs says:
void close() throws Exception
Closes this resource, relinquishing any underlying resources. This method is invoked automatically on objects managed by the try-with-resources statement.
That is why you got Socket Closed exceptions.
One more thing is that, there are too many threads in either Server or Client. Most of time such things are unnecessary, say, for a rather simple application. Because they are not quite managed well in your codes, which more likely makes your program behave unexpectedly in the future. Try use threads only if necessary, instead of using them as much as possible.
I have created a Server Socket and enabled it to listen to incoming streams.But after enabling the connection it should display a dialog Box showing message "Server Started" ,but it does not appear . I have noticed that after enabling the socket no code after that works. I have tried searching a lot about this but seem to find no suitable answer.Here is my code:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.net.*;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
public class Server
{
public Server(int i1) throws Exception{
ServerSocket MySock=new ServerSocket(i1);//opening server socket
Socket Sock=MySock.accept();//listening to client enabled
JOptionPane.showMessageDialog(null, "Server Started");
}
public static void main(String[] args) {
try {
new Server(2005);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
The problem is that ServerSocket.accept() is blocks until a connection is made..
So the JOptionPane.showMessageDialog(...) will not be executed until someone is connecting to the serversocket.
Here is a solution that handles the ServerSocket in a separate thread
import java.io.IOException;
import java.net.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import javax.swing.*;
public class Server
{
public Server(int i1) throws Exception{
Runnable serverTask = () -> {
try {
ServerSocket MySock=new ServerSocket(i1);//opening server socket
while (true) {
Socket Sock=MySock.accept();//listening to client enabled
System.out.println("Accept from " + Sock.getInetAddress());
}
} catch (IOException e) {
System.err.println("Accept failed.");
}
};
ExecutorService executorService = Executors.newSingleThreadExecutor();
executorService.submit(serverTask);
JOptionPane.showMessageDialog(null, "Server Started");
}
public static void main(String[] args) {
try {
new Server(2005);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
So, I'm making a tic tac toe project and I'm having a problem with the network part, it's all finished, only missing the part that connects players with each other, this is the class with the problem:
public class Enemy implements Runnable{
private static Socket enemy;
public Enemy(Socket sock){
enemy = sock;
}
public static void passaJogada(int xPos, int yPos){
try {
PrintWriter saida = new PrintWriter(enemy.getOutputStream());
String x = "" + xPos;
saida.println(x);
String y = "" + yPos;
System.out.print(x + y);
saida.println(y);
} catch (IOException e) {
System.out.println("Ocorreu um erro!");
}
}
public void run() {
try {
BufferedReader entrada = new BufferedReader(new InputStreamReader(enemy.getInputStream()));
while(!EndGameWindow.getEnd()) {
int x = Integer.parseInt(entrada.readLine());
int y = Integer.parseInt(entrada.readLine());
GameWindow.gameButton[x][y].fazerJogada(x,y);
}
entrada.close();
} catch (IOException e) {
System.out.println("Um errro ocorreu!");
}
}
}
and I don't have a clue of what is going on, all I know is that the PrintWriter is writing but the BufferedReader is not reading.
Just ignore the portuguese name of the variables and methods.
See the API for PrintWriter, in particular the single parameter OutputStream constructor you are using:
Creates a new PrintWriter, without automatic line flushing, from an existing OutputStream.
In other words, the PrintWriter is buffered and needs to be flushed. To enable automatic line flushing, use the appropriate constructor
PrintWriter saida = new PrintWriter(enemy.getOutputStream(), true);
...or explicitly flush the PrintWriter:
....
saida.println(y);
saida.flush();
I am assuming that you want players to play with each other even if none of them are sitting on the computer where the server "game" is. In that case what you should do is to separate the game from the networking. I am going to also assume that you have all the game part working like it should. So here is what you can do.
1) First make a class where where only the connecting to the server part is taking place , you can name it server(look below in example code).
2) Make another class to make object of these clients (in your case players).(again look at the code below)
3) Then you can have them interact with the game.
If you are having trouble fixing it, let me know maybe i can help you with more detail.
You simple server part .
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
/**
* Created by baljit on 03.05.2015.
* #author Baljit Sarai
*/
public class Server {
ServerSocket serverSocket;
public static List<ClientConnection> clientConnectionList = new ArrayList<ClientConnection>();
public Server() {
try {
serverSocket = new ServerSocket(12345);
System.out.println("Server started");
} catch (IOException ioe) {
System.out.println("Something went wrong");
}
}
public void serve(){
Socket clientSocket;
try {
while((clientSocket = serverSocket.accept()) != null){
System.out.println("got client from"+clientSocket.getInetAddress());
ClientConnection clientConnection = new ClientConnection(clientSocket);
clientConnectionList.add(clientConnection);
ClientHandler clientHandler = new ClientHandler(clientConnection,serverSocket);
clientHandler.start();
}
}catch (IOException ioe){
System.out.println("Something went wrong");
}
}
}
The clientConnection in this case can be the pllayer object you should make just to make things easier for your self.
The clientHandler is the class that can handle each player at the same time.
The "clientConnectionList" here is just to store the connections so you know where to find them.
So here is the ClientConnection class.
import java.io.*;
import java.net.Socket;
/**
* Created by baljit on 03.05.2015.
* #author Baljit Sarai
*/
public class ClientConnection {
private Socket connection;
private DataInputStream streamIn;
private DataOutputStream streamOut;
private BufferedInputStream bufferedInputStream;
public ClientConnection(Socket socket){
connection = socket;
try{
bufferedInputStream = new BufferedInputStream(connection.getInputStream());
streamIn = new DataInputStream(bufferedInputStream);
streamOut = new DataOutputStream(connection.getOutputStream());
}catch (IOException ioe){
System.out.println("Something went wrong when trying create the Connection Object");
}
}
public boolean isBound(){
return connection.isBound();
}
public DataInputStream getStreamIn() {
return streamIn;
}
public DataOutputStream getStreamOut() {
return streamOut;
}
public void close(){
try{
connection.close();
}catch (IOException ioe){
System.out.print("Something went wrong trying to close the connection");
}
}
public String getAddress(){
return connection.getInetAddress().toString();
}
}
And here is the ClientHandler Class
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
/**
* Created by baljit on 03.05.2015.
* #author Baljit Sarai
*/
public class ClientHandler extends Thread{
private ServerSocket serverSocket;
String data;
ClientConnection connection;
public ClientHandler(ClientConnection clientConnection, ServerSocket serverSocket) {
connection = clientConnection;
}
public void makeMove(String data){
//This is where you put the logic for how the server can
//interpetate the readed data to a game move
}
#Override
public void run(){
System.out.println("ClientHandler running");
try{
while(connection.isBound()){
data= connection.getStreamIn().readUTF();
this.makeMove(data);
}
connection.close();
}catch (IOException ioe){
System.out.println("Connection dead "+connection.getAddress());
Server.clientConnectionList.remove(connection);
}
}
}
Please let me know how it is working out for you. Maybe i can help you better :) good luck :)
In socket programming using Java.I want a function call to happen whenever a client connects to the server. I'm stuck up here. Any help will be appreciated.
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class NewConnectionListener implements Runnable{
public static ServerSocket serverSocket;
public NewConnectionListener(){
try {
serverSocket = new ServerSocket(500);
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void run() {
while(true){
try {
Socket s = serverSocket.accept();
callMethodWithNewSocket(s);
System.out.println("new Client");
} catch (IOException e) {
System.out.println("Error getting Client");
e.printStackTrace();
}
}
}
}
With this code everytime there is a new connection to port 500 on the server the method callMethodWithNewSocket(Socket s) will be called with the socket as a parameter.
My final project for a class is to put together a game, including multiplayer. So I started trying to figure out java networking, and I'm kind of stuck.
Each of the two game clients needs to be able to send and receive messages to and from the other client.
The way I figured I would handle this is that I have a NetworkServer and NetworkClient objects that runs in their own threads.
I was thinking that I would just start them from my main game application, but I wanted to do some testing first, so I set this project up:
NetworkClient:
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.Timer;
import java.util.TimerTask;
public class NetworkClient extends Thread {
Socket server;
ObjectOutputStream out;
Timer timer;
public NetworkClient(String hostname, int port) throws IOException
{
server = new Socket(hostname, port);
out = new ObjectOutputStream(server.getOutputStream());
timer = new Timer();
timer.schedule(new SendTask(), 0, 1*1000);
}
public void sendData(Integer b) throws IOException {
out.writeObject(b);
}
class SendTask extends TimerTask {
Integer i = new Integer(1);
public void run() {
System.out.println("Client: Sending Integer: " + i.toString());
try {
sendData(i);
i = new Integer(i.intValue()+1);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} // run()
} // class SendTask
}
NetworkServer:
import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketTimeoutException;
public class NetworkServer extends Thread {
private ServerSocket serverSocket;
private Socket client;
private Integer i;
private ObjectInputStream in;
public NetworkServer(int port) throws IOException
{
serverSocket = new ServerSocket(port);
//serverSocket.setSoTimeout(10000);
}
public void run()
{
try {
System.out.println("Waiting for client on port " + serverSocket.getLocalPort() + "...");
client = serverSocket.accept();
System.out.println("Just connected to " + client.getRemoteSocketAddress());
in = new ObjectInputStream(client.getInputStream());
} catch (IOException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
while(true)
{
try
{
i = (Integer) in.readObject();
System.out.println("Server: Received the integer: " + i.toString());
}
catch(SocketTimeoutException s)
{
System.out.println("Socket timed out!");
break;
}
catch(IOException e)
{
e.printStackTrace();
try { client.close();} catch (IOException e1) {}
break;
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
Network (The thing I'm using to try and test this):
import java.io.IOException;
public class Network {
NetworkClient client;
NetworkServer server;
public Network() throws IOException {
server = new NetworkServer(6066);
server.start();
client = new NetworkClient("192.168.1.196", 6066);
client.start();
}
public static void main(String [] args)
{
try
{
Network n = new Network();
}catch(IOException e)
{
e.printStackTrace();
}
}
}
I have the timer in there to facilitate sending data from the client to the server, which would normally be done by my game, but since I'm testing I had to have it send somehow.
When I run this where the client and server are talking to each other, I get both the Sent and Received messages.
When I put it on my laptop (and change the IP in NetworkClient to match my desktop, and vice versa on my desktop) and run it in both places, the client on the desktop sends to the server on the laptop, but the client on the laptop does not send to the server on the desktop.
And at some point during the running, I get an exception about that client's connection being reset by peer, though the working client/server connection continue.
So, I guess my question is, Does anyone know why it works in one direction but not bidirectionally?
FIXED!!
Edit: Gah, I figured it out. It had to do with the timing on starting the two servers.
I changed Network to:
import java.io.IOException;
public class Network {
NetworkClient client;
NetworkServer server;
public Network() throws IOException {
startServer();
startClient();
}
private void startServer() throws IOException {
server = new NetworkServer(6066);
server.start();
}
private void startClient(){
boolean isConnected = false;
while (!isConnected) {
try {
client = new NetworkClient("192.168.1.196", 6066);
} catch (IOException e) {
// TODO Auto-generated catch block
//e.printStackTrace();
continue;
}
isConnected = true;
}
client.start();
}
public static void main(String [] args)
{
try
{
Network n = new Network();
}catch(IOException e)
{
e.printStackTrace();
}
}
}
Edit your Firewall. Make sure that java.exe has inbound and outbound traffic enabled. Also, add a rule to your Firewall for port 6066.