Hello Experts
can somebody please indentify the problem with this server why this is unable to connect more then one client
import java.io.*;
import java.net.*;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.*;
public class MultithreadedServer extends Thread {
private ServerSocketChannel ssChannel;
private Thread tRunSer = new Thread(this, "ServerSelectThread");
public static void main(String argv[]) throws Exception {
new MultithreadedServer();
}
public MultithreadedServer() throws Exception {
this.start();
}
public void run() {
while (true) {
try {
ssChannel = ServerSocketChannel.open();
ssChannel.configureBlocking(false);
int port = 2345;
ssChannel.socket().bind(new InetSocketAddress(port));
} catch (Exception e) {
}
}
}
}
class Connect extends Thread {
private ServerSocketChannel ssChannel;
private SimManager SM;
private BallState BS = new BallState(10, 5);
public Connect(ServerSocketChannel ssChannel) {
this.ssChannel = ssChannel;
SM = new SimManager(BS);
SM.start();
}
public void run() {
try {
SocketChannel sChannel = ssChannel.accept();
while (true) {
ObjectOutputStream oos = new ObjectOutputStream(sChannel
.socket().getOutputStream());
oos.writeObject(BS);
System.out.println("Sending String is: '" + BS.X + "'" + BS.Y);
oos.flush();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
my intention is to send the objects on network.
please help
new code:
import java.io.*;
import java.net.*;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.*;
public class MultithreadedServer extends Thread {
private ServerSocketChannel ssChannel;
private SimManager SM;
private BallState BS = new BallState(10, 5);
private Thread tRunSer = new Thread(this, "ServerSelectThread");
public static void main(String argv[]) throws Exception {
new MultithreadedServer();
}
public MultithreadedServer() throws Exception {
this.start();
}
public void run() {
// create the server socket once
try {
ssChannel = ServerSocketChannel.open();
ssChannel.configureBlocking(false);
ssChannel.socket().bind(new InetSocketAddress(2345));
} catch (IOException e1) {
e1.printStackTrace();
}
while (true) {
// accept new connections on the socket
SocketChannel accept;
try {
accept = ssChannel.accept();
ObjectOutputStream oos;
oos = new ObjectOutputStream(accept.socket().getOutputStream());
oos.writeObject(BS);
System.out.println("Sending String is: '" + BS.X + "'" + BS.Y);
oos.flush();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
}
You are creating a new server socket for each loop iteration (using the same port over and over). You must create the server socket only once, and then accept new incoming connections.
Something like:
public void run() {
// create the server socket once
ssChannel = ServerSocketChannel.open();
ssChannel.configureBlocking(false);
ssChannel.socket().bind(new InetSocketAddress(2345));
while (true) {
// accept new connections on the socket
try {
SocketChannel accept = ssChannel.accept();
System.out.println("new client: " + accept.getRemoteAddress());
} catch (Exception e) {
System.out.println("exception: " + e.getMessage());
}
}
}
If you put something in your catch block you will probably find it yourself. (e.printStackTracer() might help for the time being).
Here is the reason for your NPE:
If this channel is in non-blocking mode then this method will immediately return null if
there are no pending connections.
This is from ServerSocketChannel.accept().
Your accept call returns null, and you then try to call a method on this null object.
Related
I want to make a game (jungle speed), where players click totem and it changes position on screen (I'm using swing, it's not important) and information about localisation change should be sent to everyone.
I want to make a server which gets player's click, verifies it and send update info to all.
In this scenario, client listens to server if someone has clicked totem and meanwhile is ready to send info about his own click.
Server listens to everyone and meanwhile is ready to send information to all.
I try to implement it like this:
Server generates thread for each player, listens inside for click and is ready to be interrupted to send new totem localisation (I use method shutdownNow on ExecutorService, which should cause IOException in threads which will made them to stop doing loop and send information about new localisation) then client-side gets it.
Same for client side if he clicks, thread is interrupted and instead of waiting for new localisation it sends his click.
The problem is that I can't create streams. Here is output and code
Client side:
2017-05-22T23:04:06.417Connected
2017-05-22T23:04:06.417Trying to make output
2017-05-22T23:04:06.417Trying to make input
Server side:
2017-05-22T23:04:03.278Server Thread :Socket created
2017-05-22T23:04:03.294Server Thread :Waiting for client!
2017-05-22T23:04:06.385Server Thread :Correct, connected!
2017-05-22T23:04:12.239Trying to make input
Client side code :
package client;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.time.LocalDateTime;
import java.util.logging.Level;
import java.util.logging.Logger;
public class ServerConnection implements Runnable {
MainWindow frame;
Socket toServ;
Socket fromServ;
ServerSocket myServ;
ObjectOutputStream out;
ObjectInputStream reader;
public int x, y, totemx, totemy;
int i = 0;
public ServerConnection(MainWindow frame) {
try {
this.frame = frame;
myServ = new ServerSocket(1338);
toServ = new Socket("localhost", 1337);
fromServ = myServ.accept();
System.out.println(LocalDateTime.now() + "Connected");
try {
System.out.println(LocalDateTime.now() + "Trying to make output");
out = new ObjectOutputStream(new BufferedOutputStream(toServ.getOutputStream()));
} catch (IOException ex) {
Logger.getLogger(ServerConnection.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println(LocalDateTime.now() + "Trying to make input");
reader = new ObjectInputStream(new BufferedInputStream(fromServ.getInputStream()));
} catch (IOException ex) {
Logger.getLogger(ServerConnection.class.getName()).log(Level.SEVERE, null, ex);
}
}
#Override
public void run() {
System.out.println(LocalDateTime.now() + "Running");
while (true) {
try {
int xGot, yGot;
System.out.println(LocalDateTime.now() + "Waiting for params");
xGot = (int) reader.readInt();
yGot = (int) reader.readInt();
System.out.println(LocalDateTime.now() + "I got new params");
frame.refresh(xGot, yGot);
} catch (IOException ex) {
{
try {
System.out.println(LocalDateTime.now() + "Sending click thread: Sending my click");
out.writeInt(x);
out.writeInt(y);
System.out.println(LocalDateTime.now() + "Sent");
} catch (IOException ex1) {
Logger.getLogger(ServerConnection.class.getName()).log(Level.SEVERE, null, ex1);
}
}
}
}
}
}
Server side code
First file:
package javaapplicationserwer;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.time.LocalDateTime;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* #author Japko
*/
public class Server{
public int x, y;
ServerSocket serv = null;
ExecutorService executor;
Server()
{
x = 10;
y = 50;
executor = Executors.newFixedThreadPool(4);
try {
serv = new ServerSocket(1337);
System.out.println(LocalDateTime.now() + "Server Thread :Socket created");
while (true) {
System.out.println(LocalDateTime.now() + "Server Thread :Waiting for client!");
Socket fromSocket = serv.accept();
Socket toSocket=new Socket(fromSocket.getInetAddress(),1338);
System.out.println(LocalDateTime.now() + "Server Thread :Correct, connected!");
ClientConnection temp = new ClientConnection(fromSocket,toSocket, this);
executor.submit(temp);
}
} catch (IOException ex) {
Logger.getLogger(JavaApplicationSerwer.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void updateIt(int x, int y) {
System.out.println(LocalDateTime.now() + "Updating");
if (x == this.x && y == this.y) {
Random rand = new Random();
this.x = rand.nextInt(300);
this.y = rand.nextInt(300);
System.out.println(LocalDateTime.now() + "Updated");
executor.shutdownNow();
}
System.out.println(LocalDateTime.now() + "I notify");
}
}
Second file (Class implementing runnable which is created for each player by server):
package javaapplicationserwer;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.time.LocalDateTime;
import java.util.logging.Level;
import java.util.logging.Logger;
public class ClientConnection implements Runnable {
Socket fromSocket, toSocket;
InetAddress IP;
Server serv;
ObjectOutputStream out;
ObjectInputStream reader;
public ClientConnection(Socket fromSocket, Socket toSocket, Server serwer) {
this.fromSocket = fromSocket;
this.toSocket = toSocket;
this.serv = serwer;
try {
System.out.println(LocalDateTime.now() + "Trying to make input");
reader = new ObjectInputStream(new BufferedInputStream(fromSocket.getInputStream()));
} catch (IOException ex) {
Logger.getLogger(ClientConnection.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println(LocalDateTime.now() + "Trying to make output");
try {
out = new ObjectOutputStream(new BufferedOutputStream(toSocket.getOutputStream()));
} catch (IOException ex) {
Logger.getLogger(ClientConnection.class.getName()).log(Level.SEVERE, null, ex);
}
}
#Override
public void run() {
while (true) {
System.out.println(LocalDateTime.now() + "Starting");
try {
int xGot, yGot;
while (true) {
System.out.println(LocalDateTime.now() + "Waiting for params");
try {
xGot = reader.readInt();
yGot = reader.readInt();
System.out.println(LocalDateTime.now() + "Got this");
//serv.wait();
System.out.println(LocalDateTime.now() + "Waited");
serv.updateIt(xGot, yGot);
System.out.println(LocalDateTime.now() + "Verified");
} catch (IOException ex) {
try {
out.writeInt(serv.x);
out.writeInt(serv.y);
} catch (IOException ex1) {
Logger.getLogger(ClientConnection.class.getName()).log(Level.SEVERE, null, ex1);
}
Logger.getLogger(ClientConnection.class.getName()).log(Level.SEVERE, null, ex);
}
}
} finally {
System.out.println(LocalDateTime.now() + "I'm not serving for you");
}
}
}
}
It sounds like client has mate output (which means that server has input), then client wants to create input, but server escapes from constructor and doesn't even try to make its output.
Thanks in advance for help.
Sockets are a two (2) way connection. You only need one socket in the client connection.
here is some code that does simple tcp:
package p;
import java.io.*;
import java.net.*;
import java.util.function.*;
public class Tcp {
static class Acceptor extends Thread {
Acceptor(ServerSocket serverSocket,Consumer<Socket> consumer) {
super("Acceptor");
this.serverSocket=serverSocket;
this.consumer=consumer;
}
#Override public void run() {
p("acceptor running on: "+serverSocket);
while(true)
try {
Socket socket=serverSocket.accept();
if(consumer!=null) consumer.accept(socket);
} catch(IOException e) {
p(getName()+" caught: "+e);
break;
}
}
final ServerSocket serverSocket;
final Consumer<Socket> consumer;
}
static class Connection implements Runnable {
Connection(Socket socket) throws IOException {
this.socket=socket;
in=new BufferedReader(new InputStreamReader(socket.getInputStream()));
out=new OutputStreamWriter(socket.getOutputStream());
}
boolean send(String string) {
try {
p("sending: "+string+" on: "+socket);
out.write(string+'\n'/*System.getProperty("line.separator")*/);
out.flush();
return true;
} catch(IOException e) {
e.printStackTrace();
}
return false;
}
void process(String string) {
p("connection on: "+socket+" received: "+string);
}
#Override public void run() {
p("connection on: "+socket+" is runing.");
String string=null;
try {
p("connection on: "+socket+" is trying to read.");
while((string=in.readLine())!=null) {
process(string);
}
} catch(IOException e) {
e.printStackTrace();
}
process(null);
p("connection on: "+socket+" is exiting run()");
}
final Socket socket;
final BufferedReader in;
final Writer out;
}
public static void p(String string) {
System.out.println(string);
}
Tcp(String host,Integer service) throws IOException {
ServerSocket serverSocket=new ServerSocket();
SocketAddress socketAddress=new InetSocketAddress(host,service);
serverSocket.bind(socketAddress);
Consumer<Socket> socketConsumer=(socket)-> {
p("accepted from: "+socket);
try {
final Connection connection=new Connection(socket) {
#Override void process(String string) {
super.process(string);
send(string.toUpperCase());
}
};
new Thread(connection,"incoming").start();
} catch(IOException e2) {
e2.printStackTrace();
}
};
new Acceptor(serverSocket,socketConsumer).start();
}
public static void main(String[] args) throws UnknownHostException,IOException,InterruptedException {
final String host="localhost";
final Integer service=1237;
Tcp tcp=new Tcp(host,service);
Socket socket=new Socket(host,service);
Connection c1=new Connection(socket);
new Thread(c1,"c1").start();
socket=new Socket(host,service);
Connection c2=new Connection(socket);
Thread.sleep(500);
new Thread(c2,"c2").start();
c1.send("foo");
c2.send("bar");
}
}
out.flush() helped in this case.
Scenario:
a) Persistent connections
b) Manage each server-client communication individually
c) Protect System from propagating exceptions/errors
I tried to created two instances of server socket listeners using the following code :
SimpleSocketServers.java
public class SimpleSocketServers {
public static void main(String[] args) throws Exception {
int port1 = 9876;
SimpleSocketServer server1 = new SimpleSocketServer(port1);
server1.startAndRunServer();
System.out.println("Servers : server1 Listening on port: " + port1);
int port2 = 9875;
SimpleSocketServer server2 = new SimpleSocketServer(port2);
server2.startAndRunServer();
System.out.println("Servers : server2 Listening on port: " + port2);
}
}
and
SimpleSocketServer.java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class SimpleSocketServer {
private ServerSocket serverSocket;
private int port;
public SimpleSocketServer(int port) {
this.port = port;
}
public void startAndRunServer() {
try {
System.out.println("Starting Server at port " + port + " ...");
serverSocket = new ServerSocket(port);
System.out.println("Listening for client connection ...");
Socket socket = serverSocket.accept();
RequestHandler requestHandler = new RequestHandler(socket);
requestHandler.start();
} catch (Exception e) {
e.printStackTrace();
}
}
}
class RequestHandler extends Thread {
private Socket socket;
RequestHandler(Socket socket) {
this.socket = socket;
}
#Override
public void run() {
try {
System.out.println("Client Request Response being processed...");
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream());
} catch (Exception e) {
e.printStackTrace();
}
}
}
But, it creates only one instance as control is not returning from the constructor of first instance. Is there any possibility to get back control and run both instances of server socket listeners simultaneously? (ps: Pardon me, if it is wrong or trivial!)
Use 2 Different Threads, Listening To 2 Different Ports.
Thread ServerThread1 = new Thread(new Runnable() {
#Override
public void run() {
ServerSocket ServerSocketObject = null;
while(true)
{
try {
ServerSocketObject = new ServerSocket(Your_Port_Number1);
Socket SocketObject = ServerSocketObject.accept();
// Your Code Here
SocketObject.close();
} catch (IOException e) {
try {
ServerSocketObject.close();
} catch (IOException e1) {
e1.printStackTrace();
}
e.printStackTrace();
}
}
}
});
Thread ServerThread2 = new Thread(new Runnable() {
#Override
public void run() {
ServerSocket ServerSocketObject = null;
while(true)
{
try {
ServerSocketObject = new ServerSocket(Your_Port_Number2);
Socket SocketObject = ServerSocketObject.accept();
// Your Code Here
SocketObject.close();
} catch (IOException e) {
try {
ServerSocketObject.close();
} catch (IOException e1) {
e1.printStackTrace();
}
e.printStackTrace();
}
}
}
});
ServerThread1.start();
ServerThread2.start();
You need to have SimpleSocketServer implement Runnable; start a thread with itself as the Runnable in the constructor; and run an accept() loop in the run() method. At present you're blocking in the constructor waiting for a connection, and your servers will also only handle a single connection.
The more interesting question is why you want to provide the same service on two ports.
I wrote simple client serwer, but unfortunately, I did it so chaotic and poorly that I decided to write everything from scratch. I want to write to communicate in both directions with the ability to disconnect and connect a new client. It means the client or the server sends a message and an appropriate one reads it. At the beginning all works but when i want to close client i get two errors:
java.net.SocketException: Socket closed readSocketData()
java.net.SocketException: Socket closedwriteData(String data)
Of course I understand what those errors means , but I do not understand why they show up because i have a while loop in which i check if the client is connected. Later when i try to connect a new client everything is falling apart.
I wrote 3 classes client, server and communication. Client and server inherits from communication (methods for opening and reading data streams). It all looks like that:
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class Server extends Communication{
ServerSocket serverSocket;
Socket listener;
boolean listenerLife;
public Server(int port) {
try {
serverSocket = new ServerSocket(port);
} catch (IOException e) {
System.out.println(e);
}
}
public void startListener(){
while (true){
try {
listener = serverSocket.accept();
listenerLife = true;
} catch (IOException e) {
System.out.println(e);
}
openWriter(listener);
openReader(listener);
writeServerDataThread();
new Thread(new Runnable() {
#Override
public void run() {
readData();
}
}).start();
}
}
public void writeServerDataThread(){
openLocalReader();
new Thread(new Runnable() {
#Override
public void run() {
while (true){
String data = readLocalData();
writeData(data);
}
}
}).start();
}
public void readData(){
while (listenerLife){
String data = readSocketData();
if("exit".equals(data) || data == null){
try {
listenerLife = false;
listener.close();
} catch (IOException e) {
System.out.println(e);
}
}
else {
System.out.println(data);
}
}
}
public void writeData(String data){
try {
writer.writeBytes(data + '\n');
writer.flush();
} catch (IOException e) {
System.out.println(e);
}
}
public static void main(String[] args) {
Server server = new Server(8080);
server.startListener();
}
}
import java.io.IOException;
import java.net.Socket;
public class Client extends Communication{
Socket clientSocket;
boolean clientLive;
public Client(String hostName, int port) {
try {
clientSocket = new Socket(hostName, port);
clientLive = true;
} catch (IOException e) {
System.out.println(e + "Client(String hostName, int port)");
}
}
public boolean closeConnection(String data){
if("exit".equals(data) || data == null){
try {
writeData("Zamykam klienta");
clientSocket.close();
clientLive = false;
return false;
} catch (IOException e) {
System.out.println(e + "closeConnection(String data)");
}
}
return true;
}
public void readClientData(){
new Thread(new Runnable() {
#Override
public synchronized void run() {
openLocalReader();
while (!clientSocket.isClosed()){
String data = readLocalData();
if(closeConnection(data)){
writeData(data);
}
}
}
}).start();
}
public void readServerDataThread(){
new Thread(new Runnable() {
#Override
public synchronized void run() {
while (!clientSocket.isClosed()){
String data = readSocketData();
if(closeConnection(data)){
System.out.println(data);
}
}
}
}).start();
}
public void writeData(String data){
try {
writer.writeBytes(data + '\n');
writer.flush();
} catch (IOException e) {
System.out.println(e + "writeData(String data)");
}
}
public static void main(String[] args) {
final Client client = new Client("localhost", 8080);
client.openReader(client.clientSocket);
client.openWriter(client.clientSocket);
client.readServerDataThread();
client.readClientData();
}
}
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
public class Communication {
BufferedReader reader;
BufferedReader localReader;
DataOutputStream writer;
public void openReader(Socket incomingSocket){
try {
reader = new BufferedReader(new InputStreamReader(incomingSocket.getInputStream()));
} catch (IOException e) {
System.out.println(e);
}
}
public void openWriter(Socket incomingSocket){
try {
writer = new DataOutputStream(incomingSocket.getOutputStream());
} catch (IOException e) {
System.out.println(e);
}
}
public void openLocalReader(){
localReader = new BufferedReader(new InputStreamReader(System.in));
}
public String readLocalData(){
String data = null;
try {
data = localReader.readLine();
} catch (IOException e) {
System.out.println(e + " readLocalData()");
}
return data;
}
public String readSocketData(){
String data = null;
try {
data = reader.readLine();
} catch (IOException e) {
System.out.println(e + " readSocketData()");
}
return data;
}
}
java.net.SocketException: Socket closed readSocketData()
java.net.SocketException: Socket closed writeData(String data)
Of course I understand what those errors means
They mean you closed the socket and continued to use it.
but I do not understand why they show up because i have a while loop in which i check if the client is connected.
No you don't. You have a while loop in which you check if the client socket is still open, which isn't the same thing at all ... but in any case that doesn't prevent you from using a closed socket inside the loop, for example after you close it in closeConnection(), whose return value being back to front from what it should be is doubtless causing confusion, and which is called by two threads as far as I can tell.
i am making a java socket chat program and i made it compatible for multiple connections and when a user joins it doesn't send the message "[user] Joined" to all clients just to the one that connected but i have a thread for each client if anyone can tell me why it is only sending the message to the user that recently joined i would greatly appreciate it. Here is the server code
import java.io.*;
import java.net.*;
import java.util.ArrayList;
public class server {
public ObjectInputStream input;
public ServerSocket server;
public Socket s;
public ObjectOutputStream output;
public ArrayList<Socket> users = new ArrayList<Socket>();
public class Accept implements Runnable {
public void run() {
try {
server = new ServerSocket(55555, 100);
} catch (IOException e) {
e.printStackTrace();
}
while(true) {
try {
s = server.accept();
users.add(s);
new EchoThread(s).start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public class EchoThread extends Thread {
private Socket sock;
public EchoThread(Socket s) throws IOException {
this.sock = s;
output = new ObjectOutputStream(sock.getOutputStream());
}
public void run() {
System.out.println(sock.getInetAddress() + " Connected");
try {
for(Socket s: users) {
output.writeObject(s.getInetAddress() + " Connected");
}
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
server() throws IOException {
Thread t = new Thread(new Accept());
t.start();
}
public static void main(String[] args) throws IOException {
new server();
}
}
So,
Every time someone connects to the server, u create a new EchoThread.
Each User has his own EchoThread.
Your Server role is to manage all the EchoThreads and Sockets.
output.writeObject(s.getInetAddress() + " Connected");
This only sends a message to ONE user.
Your Server should have a List of Sockets and send messages to every Sockets
public ArrayList<Socket> users = new ArrayList<Socket>();
public ArrayList<ObjectOutputStream> outputs = new ArrayList<ObjectOutputStream>();
public class Accept implements Runnable {
public void run() {
try {
server = new ServerSocket(55555, 100);
} catch (IOException e) {
e.printStackTrace();
}
while(true) {
try {
s = server.accept();
users.add(s);
outputs.add(new ObjectOutputStream(s.getOutputStream()));
for (ObjectOutputStream o: outputs) {
o.writeObject(s.getInetAddress() + " has connected");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
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.