JAVA - Sockets :: readline() not doing anything - java

I created a Network-class where I open a socket an than send requests to it.
The class:
import java.io.*;
import java.net.*;
public class Network implements Runnable {
private boolean isHost = false;
private int hostPort = 19250;
private int clientPort = 19251;
private String host = "127.0.0.1";
private String name = "";
private ServerSocket ownServer = null;
private Socket otherServer = null;
private DataOutputStream outToServer = null;
private BufferedReader inFromServer = null;
private boolean isConnected = false;
/**
* Konstruktor -
*/
Network(String name) {
this.name = name;
this.findHost();
// if no host exists, become host itself
if (this.isHost == false) {
// host da -> become client
System.out.println(this.name + ": host found");
try {
ownServer = new ServerSocket(this.clientPort);
} catch (Exception e) {
e.printStackTrace();
}
} else {
// kein host da -> become host
System.out.println(this.name + ": no host found");
try {
ownServer = new ServerSocket(this.hostPort);
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* connect() - versucht mit anderem server zu connecten fals dies noch nicht
* geschehen ist
*
* #return true/false
*/
public boolean connect() {
if (this.isConnected == false) {
try {
if (this.isHost) {
otherServer = new Socket(this.host, this.clientPort);
} else {
otherServer = new Socket(this.host, this.hostPort);
}
} catch (IOException e) {
//System.out.println(this.name + ": connect failed");
this.isConnected = false;
return false;
}
}
try {
outToServer = new DataOutputStream(otherServer.getOutputStream());
inFromServer = new BufferedReader(new InputStreamReader(
otherServer.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
}
//System.out.println(this.name + ": connect sucess");
this.isConnected = true;
return true;
}
/**
* findHost() - schaut ob ein Host existiert
*
* #return true/false
*/
private boolean findHost() {
Socket hostSocket;
try {
hostSocket = new Socket(this.host, this.getHostPort());
DataOutputStream outToServer = new DataOutputStream(
hostSocket.getOutputStream());
BufferedReader inFromServer = new BufferedReader(
new InputStreamReader(hostSocket.getInputStream()));
outToServer.writeBytes("uHost?\n");// Fragen ob Host ist
} catch (Exception e) {
this.isHost = true;
return false; // Keine Connection aufgebaut => kein Host vorhanden
}
this.isHost = false;
return true; // Es gibt schon einen Host
}
public int getClientPort() {
return this.clientPort;
}
public int getHostPort() {
return this.hostPort;
}
public boolean getIsHost() {
return this.isHost;
}
/**
* sendToOther() - schickt daten an anderen Server
*
* #param data
*/
public void sendToOther(String data) {
this.connect();
try {
this.outToServer.writeBytes(data);
this.outToServer.writeBytes("\n"); //new Line
this.outToServer.flush();
System.out.println(this.name + ": " + data
+ " :: send to other server");
} catch (IOException e) {
e.printStackTrace();
}
try {
this.outToServer.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public void run() {
// listen to income
String line = "";
try {
while (true) {
System.out.println(this.name + ":111");
while ((line = inFromServer.readLine())!= null) {
System.out.println(this.name + ":222");
System.out.println(this.name + ":recieved: " + line);
}
System.out.println(this.name + ":333");
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void readAndDo(String data) {
System.out.println(this.name + ": data recieved: " + data);
}
}
The main Method:
public class Application {
public static void main(String[] args) {
Network t1net=new Network("ss1");
Network t2net=new Network("ss2");
t1net.connect();
t2net.connect();
t1net.sendToOther("some text1");
t2net.sendToOther("sometext2");
Thread t1 = new Thread( t1net );
t1.start();
Thread t2 = new Thread( t2net );
t2.start();
}
}
the console:
ss1: no host found
ss2: host found
ss1: some text1 :: send to other server
ss2: sometext2 :: send to other server
ss2:111
ss1:111
netstat -a:
TCP 127.0.0.1:19250 49on41PCX:54538 HERGESTELLT
TCP 127.0.0.1:19250 49on41PCX:54540 HERGESTELLT
TCP 127.0.0.1:19251 49on41PCX:54539 HERGESTELLT
TCP 127.0.0.1:49156 49on41PCX:0 ABHÖREN
TCP 127.0.0.1:54538 49on41PCX:19250 HERGESTELLT
TCP 127.0.0.1:54539 49on41PCX:19251 HERGESTELLT
TCP 127.0.0.1:54540 49on41PCX:19250 HERGESTELLT
The problem is, that the Network.run() block in the readline()-command. The data is send, bu never recieved.
Thank you for helping.

You have used the sockets in a wrong manner.
ss : ServerSocket
s : Socket
You have first made two ss on two threads and made two s connecting to the the intial ss. In this way ss1 is bound to s2 and ss2 is bound to s1. And you have implemented input and output only from s1 and s2. So if you write from s1, it won't go into s2. In fact you need to create another socket from ss2 that will accept connections. And the same with ss1. I hope you get my point
Actually you should have created only one ss for the host. Then:
socketHost = ss.accept();
socketClient = new Socket(host, port);
Now you can use these two sockets for communication with each other by using their I/O streams.
In short earlier you had made two connections say a and b. You sent and received from a on one thread and sent and received data from b on the second thread.
Just look up on some tutorial of simple socket I/O and you will understand.
EDIT: See EchoClient.java and EchoServer.java from http://docs.oracle.com/javase/tutorial/networking/sockets/readingWriting.html

Related

Why can i recieve broadcasts, but not communicate with a specific socket in my App?

First some Information regarding my Setup.
I have a S8 Cellphone, where i run this App, based upon the AR-Devkit demo from Google.
public void closeSocket(DatagramSocket socket) {
if (socket != null && socket.isConnected() ) {
while (!socket.isConnected()) {
socket.disconnect();
try {
Thread.sleep(SpringAR.TIME_OUT_IN_BROADCAST);
} catch (InterruptedException e) {
Log.d(SpringAR.protocollDebugLogPrefix, " Socket Closing interrupted");
e.printStackTrace();
}
}
}
if (socket != null && !socket.isClosed()) {
socket.close();
while (!socket.isClosed()) {
try {
Thread.sleep(SpringAR.TIME_OUT_IN_BROADCAST);
} catch (InterruptedException e) {
Log.d(SpringAR.protocollDebugLogPrefix, " Socket Closing interrupted");
e.printStackTrace();
}
}
}
}
public DatagramSocket createSocket(InetAddress ipAddress, int port) {
try {
DatagramSocket socket = new DatagramSocket(null);
InetSocketAddress address = new InetSocketAddress(ipAddress, port);
socket.setReuseAddress(true);
socket.bind(address);
return socket;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public DatagramSocket getBroadcastListenerSocket() throws IOException {
InetSocketAddress anyAdress = new InetSocketAddress(InetAddress.getByName("0.0.0.0"), 9000);
DatagramSocket socket = new DatagramSocket(null);
socket.setSoTimeout(30);
socket.setReuseAddress(true);
socket.bind(anyAdress);
return socket;
}
public DatagramSocket getBroadcastSenderSocket(DatagramSocket oldSocket) {
DatagramSocket socket = null;
try {
ARDeviceAddress = InetAddress.getByName(comonUtils.getIPAddress(true));
socket = getSocket(oldSocket, ARDeviceAddress, SpringAR.UDP_SERVER_PORT, null);
socket.setBroadcast(true);
socket.setSoTimeout(SpringAR.TIME_OF_FRAME_IN_MS);
} catch (IOException e) {
e.printStackTrace();
}
return socket;
}
public DatagramSocket getSocket(DatagramSocket oldSocket, InetAddress ipAddress, int port, InetAddress targetAddress) {
if (oldSocket != null ) {
closeSocket(oldSocket);
}
DatagramSocket socket = null;
try {
socket = createSocket(ipAddress, port);
socket.setBroadcast(false);
socket.setSoTimeout(SpringAR.TIME_OF_FRAME_IN_MS);
if (targetAddress != null)
socket.connect(targetAddress, port);
} catch (SocketException e) {
e.printStackTrace();
}
return socket;
}
public class DatagramReciever extends Thread {
private String datagramToSend = "";
private boolean newDatagramToSend = false;
private DatagramPacket snd_packet;
DatagramSocket senderSocket = null;
DatagramSocket listenerSocket = null;
private DatagramSocket broadCastListenerSocket;
//Buffer gettters and setters
private int writeBuffer = 0;
private SpringAR.comStates oldState;
int getReadBuffer() {
if (writeBuffer == 1) return 0;
return 1;
}
void switchBuffer() {
recieveByteIndex = 0;
writeBuffer = getReadBuffer();
}
public String dbg_message = "";
//Management Communication Headers
public void kill() {
closeSocket(senderSocket);
closeSocket(listenerSocket);
closeSocket(broadCastListenerSocket);
}
public void run() {
try {
initializeBroadcastConnection();
while (true) {
//Recieving Datagramm
DatagramPacket rcv_packet = new DatagramPacket(rcv_message[writeBuffer], rcv_message[writeBuffer].length);
boolean NewMessageArrived = true;
try {
listenerSocket.receive(rcv_packet);
} catch (SocketTimeoutException e) {
NewMessageArrived = false;
}
//Watchdog
handleWatchDogTimer(State);
//TODO Delete String conversion
if (NewMessageArrived) {
dbg_message = new String(rcv_message[writeBuffer], 0, rcv_packet.getLength(), "US-ASCII");
Log.d(SpringAR.dataDebugLogPrefix, "" + rcv_packet.getAddress().getHostAddress() + ": " + dbg_message.trim() + " of " + rcv_packet.getLength() + "length ");
}
if (validatePackageSender(rcv_packet)) {
connectionStateMachine(rcv_message, rcv_packet);
}
//Sending Datagram
if (newDatagramToSend && hostIpAddress != null) {
//Log.d(SpringAR.protocollDebugLogPrefix, "Server sending: " + datagramToSend);
byte[] snd_message = datagramToSend.getBytes();
try {
snd_packet = packSendPackageByState(snd_message);
assert (snd_packet != null);
senderSocket.send(snd_packet);
newDatagramToSend = false;
} catch (IOException e1) {
e1.printStackTrace();
//causes Caused by: android.system.ErrnoException: sendto failed: EINVAL (Invalid argument)
Log.e(SpringAR.protocollDebugLogPrefix, "Server Error in State: " + State.name());
break;
}
}
}
} catch (IOException e1) {
e1.printStackTrace();
}
}
private void initializeBroadcastConnection() throws IOException {
ARDeviceAddress = InetAddress.getByName(comonUtils.getIPAddress(true));
senderSocket = getSocket(null, ARDeviceAddress, SpringAR.UDP_SERVER_PORT, null);
broadCastListenerSocket = getBroadcastListenerSocket();
listenerSocket = broadCastListenerSocket;
Log.d(SpringAR.protocollDebugLogPrefix, "initializeBroadcastConnection completed");
}
// handles management traffic like configurstion files
private void connectionStateMachine(byte[][] payload, DatagramPacket rcv_packet) throws IOException {
//Reset triggered by Host
if (comonUtils.indexOf(payload[writeBuffer], SpringAR.recieveResetHeaderByte) != SpringAR.STRING_NOT_FOUND) {
State = SpringAR.comStates.STATE_resetCommunication;
}
Log.d(SpringAR.protocollDebugLogPrefix, "ConnectionStateMachine: " + State.name());
switch (State) {
case STATE_resetCommunication: {
messageCounter = 0;
listenerSocket = broadCastListenerSocket;
hostIpAddress = comonUtils.getBroadcastAddress(context);
senderSocket = getBroadcastSenderSocket(senderSocket);
setSendToSpringMessage(SpringAR.sendResetHeader);
State = SpringAR.comStates.STATE_broadCastHeader;
return;
}
case STATE_broadCastHeader: {
if (comonUtils.indexOf(payload[writeBuffer], SpringAR.recieveHostReplyHeaderByte) != SpringAR.STRING_NOT_FOUND) {
Log.d(SpringAR.protocollDebugLogPrefix, " Host Reply Header recieved");
//Extract the hostIp
String hostIpAdressAsString = new String(payload[writeBuffer]);
hostIpAdressAsString = hostIpAdressAsString.replace(SpringAR.recieveHostReplyHeader, "").trim();
Log.d(SpringAR.dataDebugLogPrefix, hostIpAdressAsString);
hostIpAddress = InetAddress.getByName(hostIpAdressAsString);
//Set Connection from broadcast to target
ARDeviceAddress = InetAddress.getByName(comonUtils.getIPAddress(true));
Log.d(SpringAR.protocollDebugLogPrefix, " New Device Adress " + ARDeviceAddress);
senderSocket = getSocket(senderSocket, ARDeviceAddress, SpringAR.UDP_SERVER_PORT, hostIpAddress);
listenerSocket = senderSocket;
State = SpringAR.comStates.STATE_sendCFG;
return;
}
setSendToSpringMessage(SpringAR.sendBroadcasteHeader);
delayByMs(SpringAR.TIME_OUT_IN_BROADCAST);
return;
}
case STATE_sendCFG: {
if ( SpringAR.STRING_NOT_FOUND != comonUtils.indexOf(payload[writeBuffer], SpringAR.recieveCFGHeaderByte )) {
State = SpringAR.comStates.STATE_sendRecieveData;
return;
}
setSendToSpringMessage(SpringAR.formConfigurationMessage());
return;
}
case STATE_sendRecieveData: {
if ( SpringAR.STRING_NOT_FOUND != comonUtils.indexOf(payload[writeBuffer], SpringAR.recieveDataHeaderByte)) {
writeRecievedDataToBuffer(payload[writeBuffer], rcv_packet.getLength());
}
break;
}
default:
Log.d(SpringAR.protocollDebugLogPrefix, "Connection State Machine invalid state");
}
}
https://github.com/PicassoCT/arcore-android-sdk/blob/6c9b48a3d520e039cd48bc2af7354ccdec857736/arcore-android-sdk/samples/hello_ar/app/src/main/java/com/google/ar/core/examples/app/common/tcpClient/Server.java
All the testing is happening in a home-WiFi Setup, where the desktop with the host-application is directly attached to the WiFi-Router.
What is working thus far:
The device can broadcast its presence.
The host can broadcast its configuration.
The Device can not communicate from IP to IP on the host. Both sides have fixed IP set.
I can communicate with the App PacketSender with the host-Application, and ruled a failure on its part out.
I also built a smaller debug-loop, to only send udp-packets back and forth, which also worked.
Thank you for your time
Change this line:
socket.setSoTimeout(30);
to
socket.setSoTimeout(1000);
You've got a fairly complex state machine going here, and it's difficult to discern what is happening without having logs to look at. I would summarize your state machine like this:
Broadcast a configuration message
Spend 30ms listening for a response
If no response is received, block for SpringAR.TIME_OF_FRAME_IN_MS (not included in your code; I assume it is 1000ms), and loop back to #1
If a response was received, send a reply directly to the peer, and go to #2
#4 is the step that isn't happening. The likely reason (based on the Wireshark dump) is that it's taking 68ms for ARDevice's response to reach "Host". You only gave it 30ms. There could be a number of reasons it's taking so long, but that's beyond the scope of your question.

ClassNotFoundException across different machines

I am trying to write a messaging application in java, but keep getting an error. When I run the client on server on the same device, I get the same message. However, when I run the client and server on the same device, the client can receive messages from the server, but is unable to send a message. If I do try to send a message from the separate machine, I get the following errors:
Server has close the connection: java.io.EOFException
java.lang.ClassNotFoundException: ChatMessage
I do not know what this error means, and do not know how to fix it. I would very much appreciate some help and precise instructions on how to fix this error, and prevent it in the future.
Server Class:
public class Server {
// a unique ID for each connection
private static int uniqueId;
// an ArrayList to keep the list of the Client
private ArrayList<ClientThread> al;
// if I am in a GUI
private ServerGUI sg;
// to display time
private SimpleDateFormat sdf;
// the port number to listen for connection
private int port;
// the boolean that will be turned of to stop the server
private boolean keepGoing;
private Socket socket;
/*
* server constructor that receive the port to listen to for connection as parameter
* in console
*/
public Server(int port) {
this(port, null);
}
public Server(int port, ServerGUI sg) {
// GUI or not
this.sg = sg;
// the port
this.port = port;
// to display hh:mm:ss
sdf = new SimpleDateFormat("HH:mm:ss");
// ArrayList for the Client list
al = new ArrayList<ClientThread>();
}
public void start() {
keepGoing = true;
/* create socket server and wait for connection requests */
try
{
// the socket used by the server
ServerSocket serverSocket = new ServerSocket(port);
// infinite loop to wait for connections
while(keepGoing)
{
// format message saying we are waiting
display("Server waiting for Clients on port " + port + ".");
Socket socket = serverSocket.accept(); // accept connection
// if I was asked to stop
if(!keepGoing)
break;
ClientThread t = new ClientThread(socket); // make a thread of it
al.add(t); // save it in the ArrayList
t.start();
}
// I was asked to stop
try {
serverSocket.close();
for(int i = 0; i < al.size(); ++i) {
ClientThread tc = al.get(i);
try {
tc.sInput.close();
tc.sOutput.close();
tc.socket.close();
}
catch(IOException ioE) {
// not much I can do
}
}
}
catch(Exception e) {
display("Exception closing the server and clients: " + e);
}
}
// something went bad
catch (IOException e) {
String msg = sdf.format(new Date()) + " Exception on new ServerSocket: " + e + "\n";
display(msg);
}
}
/*
* For the GUI to stop the server
*/
protected void stop() {
keepGoing = false;
// connect to myself as Client to exit statement
// Socket socket = serverSocket.accept();
try {
new Socket("localhost", port);
}
catch(Exception e) {
// nothing I can really do
}
}
/*
* Display an event (not a message) to the console or the GUI
*/
private void display(String msg) {
String time = sdf.format(new Date()) + " " + msg;
if(sg == null)
System.out.println(time);
else
sg.appendEvent(time + "\n");
}
/*
* to broadcast a message to all Clients
*/
private synchronized void broadcast(String message) {
// add HH:mm:ss and \n to the message
String time = sdf.format(new Date());
String messageLf = time + " " + message + "\n";
// display message on console or GUI
if(sg == null)
System.out.print(messageLf);
else
sg.appendRoom(messageLf); // append in the room window
// we loop in reverse order in case we would have to remove a Client
// because it has disconnected
for(int i = al.size(); --i >= 0;) {
ClientThread ct = al.get(i);
// try to write to the Client if it fails remove it from the list
if(!ct.writeMsg(messageLf)) {
al.remove(i);
display("Disconnected Client " + ct.username + " removed from list.");
}
}
}
// for a client who logoff using the LOGOUT message
synchronized void remove(int id) {
// scan the array list until we found the Id
for(int i = 0; i < al.size(); ++i) {
ClientThread ct = al.get(i);
// found it
if(ct.id == id) {
al.remove(i);
return;
}
}
}
/*
* To run as a console application just open a console window and:
* > java Server
* > java Server portNumber
* If the port number is not specified 1500 is used
*/
public static void main(String[] args) {
// start server on port 1500 unless a PortNumber is specified
int portNumber = 1500;
switch(args.length) {
case 1:
try {
portNumber = Integer.parseInt(args[0]);
}
catch(Exception e) {
System.out.println("Invalid port number.");
System.out.println("Usage is: > java Server [portNumber]");
return;
}
case 0:
break;
default:
System.out.println("Usage is: > java Server [portNumber]");
return;
}
// create a server object and start it
Server server = new Server(portNumber);
server.start();
}
/** One instance of this thread will run for each client */
class ClientThread extends Thread {
// the socket where to listen/talk
Socket socket;
ObjectInputStream sInput;
ObjectOutputStream sOutput;
// my unique id (easier for deconnection)
int id;
// the Username of the Client
String username;
// the only type of message a will receive
ChatMessage cm;
// the date I connect
String date;
// Constructore
ClientThread(Socket socket) {
// a unique id
id = ++uniqueId;
this.socket = socket;
/* Creating both Data Stream */
System.out.println("Thread trying to create Object Input/Output Streams");
try
{
// create output first
sOutput = new ObjectOutputStream(socket.getOutputStream());
sInput = new ObjectInputStream(socket.getInputStream());
// read the username
username = (String) sInput.readObject();
display(username + " just connected.");
}
catch (IOException e) {
display("Exception creating new Input/output Streams: " + e);
return;
}
// have to catch ClassNotFoundException
// but I read a String, I am sure it will work
catch (ClassNotFoundException e) {
}
date = new Date().toString() + "\n";
}
// what will run forever
public void run() {
// to loop until LOGOUT
boolean keepGoing = true;
while(keepGoing) {
// read a String (which is an object)
try {
cm = (ChatMessage) sInput.readObject();
}
catch (IOException e) {
display(username + " Exception reading Streams: " + e);
break;
}
catch(ClassNotFoundException e2) {
display(e2.toString());
break;
}
// the messaage part of the ChatMessage
String message = cm.getMessage();
// Switch on the type of message receive
switch(cm.getType()) {
case ChatMessage.MESSAGE:
broadcast(username + ": " + message);
break;
case ChatMessage.LOGOUT:
display(username + " disconnected with a LOGOUT message.");
keepGoing = false;
break;
case ChatMessage.WHOISIN:
writeMsg("List of the users connected at " + sdf.format(new Date()) + "\n");
// scan al the users connected
for(int i = 0; i < al.size(); ++i) {
ClientThread ct = al.get(i);
writeMsg((i+1) + ") " + ct.username + " since " + ct.date);
}
break;
}
}
// remove myself from the arrayList containing the list of the
// connected Clients
remove(id);
close();
}
// try to close everything
private void close() {
// try to close the connection
try {
if(sOutput != null) sOutput.close();
}
catch(Exception e) {}
try {
if(sInput != null) sInput.close();
}
catch(Exception e) {};
try {
if(socket != null) socket.close();
}
catch (Exception e) {}
}
/*
* Write a String to the Client output stream
*/
private boolean writeMsg(String msg) {
// if Client is still connected send the message to it
if(!socket.isConnected()) {
close();
return false;
}
// write the message to the stream
try {
sOutput.writeObject(msg);
}
// if an error occurs, do not abort just inform the user
catch(IOException e) {
display("Error sending message to " + username);
display(e.toString());
}
return true;
}
}
}
Client Class:
public class Client {
// for I/O
private ObjectInputStream sInput; // to read from the socket
private ObjectOutputStream sOutput; // to write on the socket
private Socket socket;
// if I use a GUI or not
private ClientGUI cg;
// the server, the port and the username
private String server, username;
private int port;
/*
* Constructor called by console mode
* server: the server address
* port: the port number
* username: the username
*/
Client(String server, int port, String username) {
// which calls the common constructor with the GUI set to null
this(server, port, username, null);
}
/*
* Constructor call when used from a GUI
* in console mode the ClienGUI parameter is null
*/
Client(String server, int port, String username, ClientGUI cg) {
this.server = server;
this.port = port;
this.username = username;
// save if we are in GUI mode or not
this.cg = cg;
}
/*
* To start the dialog
*/
public boolean start() {
// try to connect to the server
try {
socket = new Socket(server, port);
}
// if it failed not much I can so
catch(Exception ec) {
display("Error connectiong to server:" + ec);
return false;
}
String msg = "Connection accepted " + socket.getInetAddress() + ":" + socket.getPort();
display(msg);
/* Creating both Data Stream */
try
{
sInput = new ObjectInputStream(socket.getInputStream());
sOutput = new ObjectOutputStream(socket.getOutputStream());
}
catch (IOException eIO) {
display("Exception creating new Input/output Streams: " + eIO);
return false;
}
// creates the Thread to listen from the server
new ListenFromServer().start();
// Send our username to the server this is the only message that we
// will send as a String. All other messages will be ChatMessage objects
try
{
sOutput.writeObject(username);
}
catch (IOException eIO) {
display("Exception doing login : " + eIO);
disconnect();
return false;
}
// success we inform the caller that it worked
return true;
}
/*
* To send a message to the console or the GUI
*/
private void display(String msg) {
if(cg == null)
System.out.println(msg); // println in console mode
else
cg.append(msg + "\n"); // append to the ClientGUI JTextArea (or whatever)
}
/*
* To send a message to the server
*/
void sendMessage(ChatMessage msg) {
try {
sOutput.writeObject(msg);
}
catch(IOException e) {
display("Exception writing to server: " + e);
}
}
/*
* When something goes wrong
* Close the Input/Output streams and disconnect not much to do in the catch clause
*/
private void disconnect() {
try {
if(sInput != null) sInput.close();
}
catch(Exception e) {} // not much else I can do
try {
if(sOutput != null) sOutput.close();
}
catch(Exception e) {} // not much else I can do
try{
if(socket != null) socket.close();
}
catch(Exception e) {} // not much else I can do
// inform the GUI
if(cg != null)
cg.connectionFailed();
}
/*
* To start the Client in console mode use one of the following command
* > java Client
* > java Client username
* > java Client username portNumber
* > java Client username portNumber serverAddress
* at the console prompt
* If the portNumber is not specified 1500 is used
* If the serverAddress is not specified "localHost" is used
* If the username is not specified "Anonymous" is used
* > java Client
* is equivalent to
* > java Client Anonymous 1500 localhost
* are eqquivalent
*
* In console mode, if an error occurs the program simply stops
* when a GUI id used, the GUI is informed of the disconnection
*/
public static void main(String[] args) {
// default values
int portNumber = 1500;
String serverAddress = "localHost";
String userName = "Anonymous";
// depending of the number of arguments provided we fall through
switch(args.length) {
// > javac Client username portNumber serverAddr
case 3:
serverAddress = args[2];
// > javac Client username portNumber
case 2:
try {
portNumber = Integer.parseInt(args[1]);
}
catch(Exception e) {
System.out.println("Invalid port number.");
System.out.println("Usage is: > java Client [username] [portNumber] [serverAddress]");
return;
}
// > javac Client username
case 1:
userName = args[0];
// > java Client
case 0:
break;
// invalid number of arguments
default:
System.out.println("Usage is: > java Client [username] [portNumber] {serverAddress]");
return;
}
// create the Client object
Client client = new Client(serverAddress, portNumber, userName);
// test if we can start the connection to the Server
// if it failed nothing we can do
if(!client.start())
return;
// wait for messages from user
Scanner scan = new Scanner(System.in);
// loop forever for message from the user
while(true) {
System.out.print("> ");
// read message from user
String msg = scan.nextLine();
// logout if message is LOGOUT
if(msg.equalsIgnoreCase("LOGOUT")) {
client.sendMessage(new ChatMessage(ChatMessage.LOGOUT, ""));
// break to do the disconnect
break;
}
// message WhoIsIn
else if(msg.equalsIgnoreCase("WHOISIN")) {
client.sendMessage(new ChatMessage(ChatMessage.WHOISIN, ""));
}
else { // default to ordinary message
client.sendMessage(new ChatMessage(ChatMessage.MESSAGE, msg));
}
}
// done disconnect
client.disconnect();
}
/*
* a class that waits for the message from the server and append them to the JTextArea
* if we have a GUI or simply System.out.println() it in console mode
*/
class ListenFromServer extends Thread {
public void run() {
while(true) {
try {
String msg = (String) sInput.readObject();
// if console mode print the message and add back the prompt
if(cg == null) {
System.out.println(msg);
System.out.print("> ");
}
else {
cg.append(msg);
}
}
catch(IOException e) {
display("Server has close the connection: " + e);
if(cg != null)
cg.connectionFailed();
break;
}
// can't happen with a String object but need the catch anyhow
catch(ClassNotFoundException e2) {
}
}
}
}
}
ChatMessage Class:
public class ChatMessage implements Serializable {
protected static final long serialVersionUID = 1112122200L;
// The different types of message sent by the Client
// WHOISIN to receive the list of the users connected
// MESSAGE an ordinary message
// LOGOUT to disconnect from the Server
static final int WHOISIN = 0, MESSAGE = 1, LOGOUT = 2;
private int type;
private String message;
// constructor
ChatMessage(int type, String message) {
this.type = type;
this.message = message;
}
// getters
int getType() {
return type;
}
String getMessage() {
return message;
}
}
Note that I am able to send messages just fine if I load both the server and client on the same machine. If I load the server on one machine, and the client on another, however, the client can receive messages from the server, but the server cannot receive messages from the client. If I attempt to send a message from the client to the Server, it gives me the errors shown above.

java chat program via internet [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
well, what i want to do is basically, to make a client server chat program that works over internet, ive done a basic one that works flawlessly over lan, but cant get it right over the internet..
Server :
public class Server extends javax.swing.JFrame {
HashMap<String,PrintWriter> map = new HashMap<String,PrintWriter>();
ArrayList clientOutputStreams = new ArrayList();
ArrayList<String> onlineUsers = new ArrayList();
int port = 5080;
Socket clientSock = null;
public class ClientHandler implements Runnable {
BufferedReader reader;
Socket sock;
PrintWriter client;
public ClientHandler(Socket clientSocket, PrintWriter user) {
// new inputStreamReader and then add it to a BufferedReader
client = user;
try {
sock = clientSocket;
InputStreamReader isReader = new InputStreamReader(sock.getInputStream());
reader = new BufferedReader(isReader);
System.out.println("first");
} // end try
catch (Exception ex) {
System.out.println("error beginning StreamReader");
} // end catch
} // end ClientHandler()
#Override
public void run() {
System.out.println("run method is running");
String message;
String[] data;
String connect = "Connect";
String disconnect = "Disconnect";
String chat = "Chat";
try {
while ((message = reader.readLine()) != null) {
ta1.append(message + "\n");
ta1.repaint();
System.out.println("Received: " + message);
data = message.split("#");
for (String token : data) {
System.out.println(token);
}
System.out.println(data[data.length - 1] + " datalast");
if (data[2].equals(connect)) {
tellEveryone((data[0] + "#" + data[1] + "#" + chat));
userAdd(data[0]);
map.put(data[0], client);
} else if (data[2].equals(disconnect)) {
System.out.println("barpppppppppp");
tellEveryone((data[0] + "#has disconnected." + "#" + chat));
userRemove(data[0]);
map.remove(data[0]);
} else if (data[2].equals(chat)) {
tellEveryone(message);
} else {
System.out.println("No Conditions were met.");
}
} // end while
} // end try
catch (Exception ex) {
System.out.println("lost a connection");
System.out.println(ex.getMessage());
clientOutputStreams.remove(client);
} // end catch
} // end run()
}
public void go() {
// clientOutputStreams = new ArrayList();
try {
ServerSocket serverSock = new ServerSocket(port);
System.out.println("ServerSocket Created !");
System.out.println("Started listening to port " + port);
while (true) {
// set up the server writer function and then begin at the same
// the listener using the Runnable and Thread
clientSock = serverSock.accept();
PrintWriter writer = new PrintWriter(clientSock.getOutputStream());
ta1.append(writer + " ");
ta1.repaint();
System.out.println(writer);
clientOutputStreams.add(writer);
//data_of_names_and_output_streams.add(writer.toString());
// use a Runnable to start a 'second main method that will run
// the listener
Thread listener = new Thread(new Server.ClientHandler(clientSock, writer));
listener.start();
System.out.println("Server Thread for 'new player' was started");
System.out.println("got a connection");
} // end while
} // end try
catch (Exception ex) {
System.out.println("error making a connection");
} // end catch
} // end go()
public void userAdd(String data) {
String message;
String add = "# #Connect", done = "Server# #Done";
onlineUsers.add(data);
String[] tempList = new String[(onlineUsers.size())];
onlineUsers.toArray(tempList);
for (String token : tempList) {
message = (token + add);
tellEveryone(message);
System.out.println(message);
}
tellEveryone(done);
}
public void userRemove(String data) {
System.out.println(onlineUsers.size() + " is size of online users");
System.out.println(clientOutputStreams.size() + " is size of ous");
String message;
String add = "# #Connect", done = "Server# #Done";
onlineUsers.remove(data);
String[] tempList = new String[(onlineUsers.size())];
onlineUsers.toArray(tempList);
for (String token : tempList) {
message = (token + add);
tellEveryone(message);
}
tellEveryone(done);
}
public void tellEveryone(String message) {
System.out.println(onlineUsers.size() + " is size of online users");
System.out.println(clientOutputStreams.size() + " is size of ous");
// jButton1.doClick();
// sends message to everyone connected to server
Iterator it = clientOutputStreams.iterator();
if (message.length() < 250) {
System.out.println("inside it");
while (it.hasNext()) {
try {
PrintWriter writer = (PrintWriter) it.next();
writer.println(message);
// l1.setText(message);
System.out.println("Sending " + message);
writer.flush();
} // end try
catch (Exception ex) {
System.out.println("error telling everyone");
} // end catch
}
} else {
try {
clientSock.close();
} catch (IOException ex) {
Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
/**
* Creates new form Server
*/
public Server() {
initComponents();
ta1.repaint();
}
public static void main(String args[]) throws Exception {
UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Server().setVisible(true);
}
});
new Server().go();
}
} //end form
Client : jbutton1 is setting up connection,jbutton2 sends the message.
public class Client extends javax.swing.JFrame {
boolean sent, receive;
SimpleDateFormat sdf;
String ip;
String username;
Socket sock;
BufferedReader reader;
PrintWriter writer;
ArrayList<String> userList = new ArrayList();
Boolean isConnected = false;
DefaultListModel dlm;
public Client() {
initComponents();
dlm = (DefaultListModel) l1.getModel();
ip = JOptionPane.showInputDialog("Enter the IP of the server to connect");
}
public class IncomingReader implements Runnable {
public void run() {
String stream;
String[] data;
String done = "Done", connect = "Connect", disconnect = "Disconnect", chat = "Chat", battlerequest = "battlerequest";
try {
while ((stream = reader.readLine()) != null) {
data = stream.split("#");
System.out.println(stream + " ------------------------ data");
if (data[2].equals(chat)) {
sdf = new SimpleDateFormat("HH:mm:ss");
t.append("(" + sdf.format(new Date()) + ") " + data[0] + ": " + data[1] + "\n");
//t.setText("<html><b>hi" + 3 + 3 + "</b></html>");
} else if (data[2].equals(connect)) {
t.removeAll();
userAdd(data[0]);
} else if (data[2].equals(disconnect)) {
userRemove(data[0]);
} else if (data[2].equals(done)) {
dlm.removeAllElements();
writeUsers();
userList.clear();
} else {
System.out.println("no condition met - " + stream);
}
}
} catch (Exception ex) {
System.out.println(ex.getMessage() + " hi");
}
}
}
public void ListenThread() {
Thread IncomingReader = new Thread(new Client.IncomingReader());
IncomingReader.start();
}
public void userAdd(String data) {
userList.add(data);
}
public void userRemove(String data) {
t.setText(t1.getText() + data + " has disconnected.\n");
}
public void writeUsers() {
String[] tempList = new String[(userList.size())];
userList.toArray(tempList);
for (String token : tempList) {
//ul.append( token + "\n");
dlm.addElement(token);
// ul.setText(ul.getText() + token + '\n');
}
}
public void sendDisconnect() {
String bye = (username + "# #Disconnect");
try {
writer.println(bye); // Sends server the disconnect signal.
writer.flush(); // flushes the buffer
} catch (Exception e) {
t.append("Could not send Disconnect message.\n");
}
}
public void Disconnect() {
try {
t.append("Disconnected.\n");
sock.close();
} catch (Exception ex) {
t.append("Failed to disconnect. \n");
}
isConnected = false;
n.setEditable(true);
dlm.removeAllElements();
// ul.setText("");
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
if (isConnected == false && !n.getText().equals("")) {
username = n.getText();
n.setEditable(false);
try {
sock = new Socket(ip, 5080);
InputStreamReader streamreader = new InputStreamReader(sock.getInputStream());
reader = new BufferedReader(streamreader);
writer = new PrintWriter(sock.getOutputStream());
writer.println(username + "#has connected.#Connect"); // Displays to everyone that user connected.
writer.flush(); // flushes the buffer
isConnected = true;
jLabel4.setText(n.getText());
//t.append( "<html><font color = \"black\"><b>Server : Welcome,</b></font></html>"+username);
//t1.setText("<html><font color=\"red\">yo</font></html>");
// Used to see if the client is connected.
} catch (Exception ex) {
t.append("Cannot Connect! Try Again. \n");
n.setEditable(true);
}
ListenThread();
} else if (isConnected == true) {
t.append("You are already connected. \n");
} else if (n.getText().equals("")) {
t.append("Enter a valid name \n");
}
}
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
String nothing = "";
if ((t1.getText()).equals(nothing)) {
t1.setText("");
t1.requestFocus();
} else {
try {
writer.println(username + "#" + t1.getText() + "#" + "Chat");
writer.flush(); // flushes the buffer
} catch (Exception ex) {
t.append("Message was not sent. \n");
}
t1.setText("");
t1.requestFocus();
}
t1.setText("");
t1.requestFocus(); // TODO add your handling code here:
}
private void dicsActionPerformed(java.awt.event.ActionEvent evt) {
sendDisconnect();
Disconnect(); // TODO add your handling code here:
}
i have also port forwarded the ports i am going to use - ie. 5080
now when my friend opens the client program from his computer from his home, i tell him to enter the ip as 192.168.1.2 coz thats what is saved when i open cmd and type ipconfig....
sometimes i think that the ip address i gave him is wrong coz 192.168.1.2 is i guess lan or internal ip address, so then, so do i do ? where do i get the correct ip address ? or is something else wrong in my code ?
192.168.1.2 is a non-routable IP. Click here to get your current external IP (unless your IP address is static, it may change periodically).
If you were to sign up for a dynamic dns service (here for example), then you could give your friend a "domain name" (e.g. something.dnsdynamic.com) and the service would update when your IP address changes.

Multiple Client Threads can connect, threads are accepted in sequential order

I'm trying to write a bidding application, and have a server (and thread handler), and Client (and client handler).
Currently, multiple clients can connect fine, but the first client to connect gets the opening messages, and only after the first client has proceeded to the 3rd interaction(between Client and Server), does the next Client in the list get the starting message.
I'm not entirely sure what's causing it, as it's adding a new thread each time. It's simply not showing contents of writeUTF() to all the clients at the same time.
I want to know what I'm doing wrong, and why I can't get multiple clients to start the auction at the same time. Here's my code.
Client Thread and Client
import java.net.*;
import java.io.*;
import java.util.*;
public class Client implements Runnable
{ private Socket socket = null;
private Thread thread = null;
private BufferedReader console = null;
private DataOutputStream streamOut = null;
private ClientThread client = null;
private String chatName;
public Client(String serverName, int serverPort, String name)
{
System.out.println("Establishing connection. Please wait ...");
this.chatName = name;
try{
socket = new Socket(serverName, serverPort);
System.out.println("Connected: " + socket);
start();
}
catch(UnknownHostException uhe){
System.out.println("Host unknown: " + uhe.getMessage());
}
catch(IOException ioe){
System.out.println("Unexpected exception: " + ioe.getMessage());
}
}
public void run()
{
while (thread != null){
try {
//String message = chatName + " > " + console.readLine();
String message = console.readLine();
streamOut.writeUTF(message);
streamOut.flush();
}
catch(IOException ioe)
{ System.out.println("Sending error: " + ioe.getMessage());
stop();
}
}
}
public void handle(String msg)
{ if (msg.equals(".bye"))
{ System.out.println("Good bye. Press RETURN to exit ...");
stop();
}
else
System.out.println(msg);
}
public void start() throws IOException
{
console = new BufferedReader(new InputStreamReader(System.in));
streamOut = new DataOutputStream(socket.getOutputStream());
if (thread == null)
{ client = new ClientThread(this, socket);
thread = new Thread(this);
thread.start();
}
}
public void stop()
{
try
{ if (console != null) console.close();
if (streamOut != null) streamOut.close();
if (socket != null) socket.close();
}
catch(IOException ioe)
{
System.out.println("Error closing ...");
}
client.close();
thread = null;
}
public static void main(String args[])
{ Client client = null;
if (args.length != 3)
System.out.println("Usage: java Client host port name");
else
client = new Client(args[0], Integer.parseInt(args[1]), args[2]);
}
}
import java.net.*;
import java.io.*;
import java.util.*;
import java.net.*;
Client Thread
public class ClientThread extends Thread
{ private Socket socket = null;
private Client client = null;
private DataInputStream streamIn = null;
private DataOutputStream streamOut = null;
private BufferedReader console;
private String message, bidMessage;
public ClientThread(Client _client, Socket _socket)
{ client = _client;
socket = _socket;
open();
start();
}
public void open()
{ try
{
streamIn = new DataInputStream(socket.getInputStream());
String auction = streamIn.readUTF(); // Commence auction/
System.out.println(auction);
String item = streamIn.readUTF();
System.out.println(item);
Scanner scanner = new Scanner(System.in);
streamOut = new DataOutputStream(socket.getOutputStream());
message = scanner.next();
streamOut.writeUTF(message);
streamOut.flush();
String reply = streamIn.readUTF();
System.out.println(reply);
bidMessage = scanner.next();
streamOut.writeUTF(bidMessage);
streamOut.flush();
}
catch(IOException ioe)
{
System.out.println("Error getting input stream: " + ioe);
client.stop();
}
}
public void close()
{ try
{ if (streamIn != null) streamIn.close();
}
catch(IOException ioe)
{ System.out.println("Error closing input stream: " + ioe);
}
}
public void run()
{
while (true && client!= null){
try {
client.handle(streamIn.readUTF());
}
catch(IOException ioe)
{
client = null;
System.out.println("Listening error: " + ioe.getMessage());
}
}
}
}
BidServer
import java.net.*;
import java.io.*;
public class BidServer implements Runnable
{
// Array of clients
private BidServerThread clients[] = new BidServerThread[50];
private ServerSocket server = null;
private Thread thread = null;
private int clientCount = 0;
public BidServer(int port)
{
try {
System.out.println("Binding to port " + port + ", please wait ...");
server = new ServerSocket(port);
System.out.println("Server started: " + server.getInetAddress());
start();
}
catch(IOException ioe)
{
System.out.println("Can not bind to port " + port + ": " + ioe.getMessage());
}
}
public void run()
{
while (thread != null)
{
try{
System.out.println("Waiting for a client ...");
addThread(server.accept());
int pause = (int)(Math.random()*3000);
Thread.sleep(pause);
}
catch(IOException ioe){
System.out.println("Server accept error: " + ioe);
stop();
}
catch (InterruptedException e){
System.out.println(e);
}
}
}
public void start()
{
if (thread == null) {
thread = new Thread(this);
thread.start();
}
}
public void stop(){
thread = null;
}
private int findClient(int ID)
{
for (int i = 0; i < clientCount; i++)
if (clients[i].getID() == ID)
return i;
return -1;
}
public synchronized void broadcast(int ID, String input)
{
if (input.equals(".bye")){
clients[findClient(ID)].send(".bye");
remove(ID);
}
else
for (int i = 0; i < clientCount; i++){
if(clients[i].getID() != ID)
clients[i].send(ID + ": " + input); // sends messages to clients
}
notifyAll();
}
public synchronized void remove(int ID)
{
int pos = findClient(ID);
if (pos >= 0){
BidServerThread toTerminate = clients[pos];
System.out.println("Removing client thread " + ID + " at " + pos);
if (pos < clientCount-1)
for (int i = pos+1; i < clientCount; i++)
clients[i-1] = clients[i];
clientCount--;
try{
toTerminate.close();
}
catch(IOException ioe)
{
System.out.println("Error closing thread: " + ioe);
}
toTerminate = null;
System.out.println("Client " + pos + " removed");
notifyAll();
}
}
private void addThread(Socket socket) throws InterruptedException
{
if (clientCount < clients.length){
System.out.println("Client accepted: " + socket);
clients[clientCount] = new BidServerThread(this, socket);
try{
clients[clientCount].open();
clients[clientCount].start();
clientCount++;
}
catch(IOException ioe){
System.out.println("Error opening thread: " + ioe);
}
}
else
System.out.println("Client refused: maximum " + clients.length + " reached.");
}
public static void main(String args[]) {
BidServer server = null;
if (args.length != 1)
System.out.println("Usage: java BidServer port");
else
server = new BidServer(Integer.parseInt(args[0]));
}
}
BidServerThread
import java.net.*;
import java.awt.List;
import java.io.*;
import java.awt.*;
import java.util.*;
import java.util.concurrent.BrokenBarrierException;
public class BidServerThread extends Thread
{ private BidServer server = null;
private Socket socket = null;
private int ID = -1;
private DataInputStream streamIn = null;
private DataOutputStream streamOut = null;
private Thread thread;
private String auctionStart, bid,bidMade,clientBid;
private String invalidBid;
int firstVal;
ArrayList<Bid> items = new ArrayList<Bid>();
//items.add(new Bid());
//items
//items
//items.add(new Bid("Red Bike",0));
public BidServerThread(BidServer _server, Socket _socket)
{
super();
server = _server;
socket = _socket;
ID = socket.getPort();
}
public void send(String msg)
{
try{
streamOut.writeUTF(msg);
streamOut.flush();
}
catch(IOException ioe)
{
System.out.println(ID + " ERROR sending: " + ioe.getMessage());
server.remove(ID);
thread=null;
}
}
public int getID(){
return ID;
}
public void run()
{
System.out.println("Server Thread " + ID + " running.");
thread = new Thread(this);
while (true){
try{
server.broadcast(ID, streamIn.readUTF());
int pause = (int)(Math.random()*3000);
Thread.sleep(pause);
}
catch (InterruptedException e)
{
System.out.println(e);
}
catch(IOException ioe){
System.out.println(ID + " ERROR reading: " + ioe.getMessage());
server.remove(ID);
thread = null;
}
}
}
public void open() throws IOException, InterruptedException
{
streamIn = new DataInputStream(new
BufferedInputStream(socket.getInputStream()));
streamOut = new DataOutputStream(new
BufferedOutputStream(socket.getOutputStream()));
String msg2 = "Welcome to the auction,do you wish to start?";
streamOut.writeUTF(msg2);
streamOut.flush();
String auctionStart;
String bid;
String firstMessage = streamIn.readUTF().toLowerCase();
CharSequence yes ="yes";
CharSequence no = "no";
if(firstMessage.contains(yes))
{
commenceBid();
}
else if(firstMessage.contains(no))
{
auctionStart ="Unfortunately, you cannot proceed. Closing connection";
System.out.println(auctionStart);
streamOut.writeUTF(auctionStart);
streamOut.flush();
int pause = (int)(Math.random()*2000);
Thread.sleep(pause);
socket.close();
}
else if(!firstMessage.contains(yes) && !firstMessage.contains(no))
{
System.out.println("Client has entered incorrect data");
open();
}
}
private void commenceBid() throws IOException {
items.add(new Bid("Yellow Bike",0));
items.add(new Bid("Red Bike",0));
//items.add(new Bid("Green bike",0));
String auctionStart = "Auction will commence now. First item is:\n" + items.get(0).getName();
String bidCommence = "Make a bid, whole number please.";
synchronized (server) {
server.broadcast(ID, bidCommence);
}
System.out.println("item value is" + items.get(0).getValue());
streamOut.writeUTF(auctionStart);
streamOut.flush();
streamOut.writeUTF(bidCommence);
streamOut.flush();
bidMade();
}
private void bidMade() throws IOException {
bidMade = streamIn.readUTF();
if(bidMade.matches(".*\\d.*"))
{
int bid = Integer.parseInt(bidMade);
if(bid <= items.get(0).getValue())
{
String lowBid = "Latest bid is too low, please bid higher than the current bid " + items.get(0).getValue();
streamOut.writeUTF(lowBid);
streamOut.flush();
commenceBid();
}
if (bid > items.get(0).getValue()) {
items.get(0).setValue(bid);
String bidItem = "value of current bid is: " + items.get(0).getValue();
streamOut.writeUTF(bidItem);
streamOut.flush();
System.out.println("Current bid: " + items.get(0).getValue());
String continueBid = "If you want to make another bid, say yes";
streamOut.writeUTF(continueBid);
String continueBidReply = streamIn.readUTF();
{
if(continueBidReply.contains("yes") || continueBidReply.contains("Yes"))
{
commenceBid();
}
if(continueBidReply.contains("No") || continueBidReply.contains("No"))
{
socket.close();
}
}
streamOut.flush();
}
}
else
{
invalidBid = "You have made an invalid bid, please choose a number";
streamOut.writeUTF(invalidBid);
streamOut.flush();
}
}
public void close() throws IOException
{
if (socket != null)
socket.close();
if (streamIn != null)
streamIn.close();
if (streamOut != null)
streamOut.close();
}
}
BidServerThread.open() is called before the thread is started in BidServer.addThread(). This blocks the BidServer (and prevents it from accepting other clients) until the call has returned.
BidServerThread.open() does various synchronous stuff interacting with the client ("do you wish to start?", "yes"/"no" etc.). It eventually calls itself recursively (loop) and it calls commenceBid() which in turn may call bidMade() which in turn may recur to commenceBid() in the course of synchronous interaction with the client. It is possible to have a scenario in which you have 3 interactions before this ends.
I guess, you could call BidServerThread.open() from BidServerThread.run() instead of in BidServer.addThread() in order for it to run in its thread asynchronously. (Thread.start() calls Thread.run().)

Java thread illegal state exception

In a pice of code in which a class start a thread calling start method.
it throw an illegalstate exception. But if i call run() it gose well.
Can you expain me why ?
class A{
void methodA(){
T t = new T();
t.start(); // illegal state exception
t.run(); ///ok
}
}
class T extends Thread{
....
....
}
real code:
public class FileMultiServer
{
private static Logger _logger = Logger.getLogger("FileMultiServer");
public static void main(String[] args)
{
ServerSocket serverSocket = null;
boolean listening = true;
String host = "localhost";
int porta = 4444;
InetSocketAddress addr = null;
String archiveDir = System.getProperty("java.io.tmpdir");
Aes aes = new Aes();
Properties prop = new Properties();
//load a properties file
File propFile = new File("config.properties");
try {
System.out.println(propFile.getCanonicalPath());
prop.load(new FileInputStream("config.properties"));
} catch (Exception e1) {
// TODO Auto-generated catch block
System.out.println(e1);
}
DBConnector.dbName = prop.getProperty("database");
DBConnector.ipDb = prop.getProperty("urlDb");
DBConnector.dbPort = prop.getProperty("dbport");
DBConnector.userName = prop.getProperty("dbuser");
DBConnector.password = aes.DeCrypt(prop.getProperty("dbpassword"));
String agent_address = prop.getProperty("agent_ip");
String agent_port = prop.getProperty("agent_port");
try {
WDAgent m_agent = new WDAgent(agent_address, Integer.parseInt(agent_port));
m_agent.run();
} catch (NumberFormatException e1) {
// TODO Auto-generated catch block
System.out.println("errore nell'agent");
e1.printStackTrace();
} catch (Exception e1) {
// TODO Auto-generated catch block
StringWriter errors = new StringWriter();
e1.printStackTrace(new PrintWriter(errors));
_logger.debug(e1.getMessage());
_logger.debug(errors.toString());
System.out.println(e1.getMessage());
System.out.println(errors.toString());
}
String logCfg = System.getProperty("LOG");
if (logCfg != null) DOMConfigurator.configure(logCfg); else
DOMConfigurator.configure("log4j.xml");
try
{
if (args.length == 0) {
host = "localhost";
porta = 4444;
}
else if (args.length == 1) {
porta = Integer.parseInt(args[0]);
} else if (args.length == 2) {
host = args[0];
porta = Integer.parseInt(args[1]);
} else if (args.length == 3) {
host = args[0];
porta = Integer.parseInt(args[1]);
archiveDir = args[2];
} else {
_logger.info("usage: server <host> <port> | server [port] | server");
System.exit(88);
}
} catch (Exception e) {
_logger.error(e.getMessage());
_logger.info("enter a numer for argument or nothing....");
System.exit(88);
}
_logger.info("Allocating listen to: " + host + ":" + porta);
try
{
addr = new InetSocketAddress(host, porta);
serverSocket = new ServerSocket();
serverSocket.bind(addr);
} catch (Exception e) {
_logger.error(e.getMessage());
_logger.error("Could not listen on port: " + porta);
System.exit(-1);
}
_logger.info("Server listening on " + host + "-" + addr.getAddress().getHostAddress() + ":" + porta);
while (listening) {
try {
new FileMultiServerThread(serverSocket.accept(), archiveDir).start();
} catch (Exception e) {
// TODO Auto-generated catch block
System.out.println(e);
}
}
try {
serverSocket.close();
} catch (Exception e) {
// TODO Auto-generated catch block
System.out.println(e);
}
}
}
class extends thread:
public class WDAgent extends Thread
{
private String _PID=null;
// *************************************************************************
// private - static final
// *************************************************************************
DatagramSocket socket;
boolean m_shutdown = false;
private static final Logger m_logger = Logger.getLogger(WDAgent.class);
private String getPID() {
try {
String ppid=System.getProperty("pid");
String match= "-Dpid="+ppid;
Runtime runtime = Runtime.getRuntime();
String cmd="/bin/ps -ef ";
Process process = runtime.exec(cmd);
InputStream is = process.getInputStream();
InputStreamReader osr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(osr);
String line;
while ((line = br.readLine()) != null) {
m_logger.info("line 0: "+line);
if(line.indexOf(match)!=-1 ) {
m_logger.info("line: "+line);
String[] cols=line.split(" ");
int count=0;
String val=null;
for (int k=0; k<cols.length; k++) {
if(cols[k].length()==0) continue;
count++;
if(count==3) {
// Good. I answerd the question
String pid = val;
m_logger.debug("pid processo: " + pid);
return pid;
}
val=cols[k];
}
}
}
}
catch (Exception err)
{
m_logger.error("Error retrieving PID....", err);
err.printStackTrace();
}
return null;
}
public WDAgent(String address, int port) throws IOException
{
InetSocketAddress isa = new InetSocketAddress(address, port);
socket = new DatagramSocket(isa);
m_logger.info("Agent started on (" + address + ":" + port + ")");
m_logger.info("Waiting for WD connection.");
this.start();
}
void Finalize() throws IOException
{
m_logger.info("Closing Agent.");
socket.close();
m_logger.info("Agent Closed");
}
public void Shutdown()
{
m_shutdown = true;
}
public void run()
{
byte[] buffer = new byte[1024];
int i;
while(!m_shutdown)
{
try {
String answer = "Agent PID=123456";
for (i=0; i<1024; i++)
buffer[i] = 0;
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
socket.receive(packet);
String received = new String(packet.getData(), 0, packet.getLength());
InetAddress client = packet.getAddress();
int client_port = packet.getPort();
m_logger.info("Received " + received + " from " + client);
if ((received.indexOf("PID") > 0) && (received.indexOf("ASK") > 0))
{
if(_PID==null) {
_PID=getPID();
}
if(_PID!=null) {
answer = "Agent PID=" + _PID;
m_logger.debug("risposta: " + answer);
DatagramPacket answ_packet = new DatagramPacket(answer.getBytes(), answer.getBytes().length, client, client_port);
socket.send(answ_packet);
} else {
m_logger.error("no PID per rispondere a watchdog .... sorry");
}
}
else
m_logger.warn("Command not recognized");
}
catch(IOException e)
{
m_logger.error(e.getMessage());
}
catch(Exception e)
{
m_logger.error(e.getMessage());
}
}
}
}
Well, if you call run(), you're just calling a method in your current thread. With start() you're attempting to start the Thread, and if it has for example already been started (or it has already stopped), you'll get an IllegalStateException.
ummm... you have already started the WDAgent Thread at constructor, so when you are trying to start again it thorws IllegalStateException.
You wanted to start it here:
...
try {
WDAgent m_agent = new WDAgent(agent_address, Integer.parseInt(agent_port));
m_agent.run(); // <-- Run that you wanted to be a start
} catch (NumberFormatException e1) {
...
But it was started in the constructor:
public WDAgent(String address, int port) throws IOException
{
InetSocketAddress isa = new InetSocketAddress(address, port);
socket = new DatagramSocket(isa);
m_logger.info("Agent started on (" + address + ":" + port + ")");
m_logger.info("Waiting for WD connection.");
this.start(); // <<----- It was already started here!!!!
}
You are running the run method twice, once in the new thread (you start it in the constructor) and one in the main thread by calling run.
t.start() is used to start the thread's execution. t.start() is used one time only. If you want to a run the thread again you will need to use t.run().

Categories

Resources