Java thread illegal state exception - java

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().

Related

Java StreamCorrupted when connecting more than one Client to Server

Explanation
I'm currently trying to create a Multiplayer Game with Java where up to five Players can play together.
The problem is that when I'm trying to connect multiple Clients to my Server I get an Exception and the Server doesn't work anymore.
With one Client at a time, everything works fine.
So what I need is a Server that can handle up to five players at a time and the clients should always get some new game data from the Server
every few seconds (Connected Players, etc.).
The "Game data" in the code below is the String I'm sending through the Object Stream.
Normally I would send an Object which has all the game data, but with the String, I get the same problem.
I'm struggling with the problem that only one Client can connect without any errors occurring for some days now and I didn't find a solution to my problem.
I saw that there are things like java.nio or the ExecutorService, but I didn't really understand those that much, so I don't know if they can help.
I have made a smaller program that simulates the same problem I get with my bigger program.
To Start the Server, you need to Start the GameMultiPlayerCreate.java Class, and for the Client, the Client.java class.
I'm new to Sockets so if something is unnecessary or if something can be made better please let me know.
So the Error I'm getting when I connect two or more Clients is:
java.io.StreamCorruptedException: invalid stream header: 00050131
at java.io.ObjectInputStream.readStreamHeader(Unknown Source)
at java.io.ObjectInputStream.<init>(Unknown Source)
at Server.waitForData(Server.java:89) //I highlighted that in the code with a comment
at Server.loopWaitForData(Server.java:49)
at Server.run(Server.java:34)
at java.lang.Thread.run(Unknown Source)
Code
GameMultiPlayerCreate.java: Should start the Server threads if a Client connects
public class GameMultiPlayerCreate {
ServerSocket socketServer = null;
static String settingIp = "localhost";
static String settingPort = "22222";
static byte settingPlayers = 5;
public static int connectedPlayers = 0;
public static void main(String[] args) {
try {
GameMultiPlayerCreate objGameMultiPlayerCreate = new GameMultiPlayerCreate();
objGameMultiPlayerCreate.createServer();
} catch (NumberFormatException | IOException | InterruptedException e) {
e.printStackTrace();
}
}
public void createServer() throws NumberFormatException, UnknownHostException, IOException, InterruptedException {
while (connectedPlayers < settingPlayers) {
socketServer = new ServerSocket(Integer.parseInt(settingPort), 8, InetAddress.getByName(settingIp));
System.out.println("Server is waiting for connection...");
Socket socket = socketServer.accept();
new Thread(new Server(socket)).start();
Thread.sleep(5000);
socketServer.close();
}
}
}
Server.java: This is the Class of which a new Thread should be created for each connected Client (Client Handler)
public class Server implements Runnable {
protected static Socket socket = null;
private int loops;
private int maxLoops = 10;
private int timeout = 10000;
protected static boolean killThread = false;
private boolean authenticated = true; //true for testing
protected static String ip;
protected static int port;
public Server(Socket socket) throws IOException {
Server.socket = socket;
}
public void run() {
try {
socket.setSoTimeout(timeout);
} catch (SocketException e) {
System.out.println("Error while trying to set Socket timeout. ");
System.out.println("Closing Thread..." + Thread.currentThread());
disconnectClient();
}
if (!killThread) {
GameMultiPlayerCreate.connectedPlayers = GameMultiPlayerCreate.connectedPlayers + 1;
loopWaitForData();
}
}
private void disconnectClient() {
System.out.println("Kicking Client... " + Thread.currentThread());
killThread = true;
GameMultiPlayerCreate.connectedPlayers = GameMultiPlayerCreate.connectedPlayers - 1;
}
public void loopWaitForData() {
while (!killThread) {
System.out.println(maxLoops + ", " + loops);
if (maxLoops - loops > 0) {
try {
waitForData();
} catch (SocketTimeoutException e) {
System.out.println("Error occurred while waiting for Data. Thread disconnected? Sending reminder. " + Thread.currentThread());
if (!authenticated) {
System.out.println("Kicking Client: Not authenticated");
disconnectClient();
} else {
commandReminder();
}
} catch (ClassNotFoundException | IOException e) {
loops = loops + 1;
System.out.println("Error occurred while waiting for Data. Waiting for more Data. " + Thread.currentThread());
e.printStackTrace();
loopWaitForData();
}
} else if (maxLoops - loops == 0) {
System.out.println("Error occurred while waiting for Data. Maximum trys reached. Disbanding connection. " + Thread.currentThread());
disconnectClient();
loops = loops + 1;
} else {
System.out.println("Closing Thread..." + Thread.currentThread());
disconnectClient();
}
}
}
private void commandReminder() {
System.out.println("Reminder");
try {
String code = new String("0");
ObjectOutputStream outputObject = new ObjectOutputStream(Server.socket.getOutputStream());
outputObject.writeObject(code);
} catch (IOException e) {
System.out.println("Error occurred while trying to authenticate Client: " + e + " in " + Thread.currentThread());
}
}
public void waitForData() throws IOException, ClassNotFoundException {
String code;
System.out.println("Waiting for Data...");
//Next line is where the error occurres
ObjectInputStream inputObject = new ObjectInputStream(socket.getInputStream());
while ((code = (String) inputObject.readObject()) != null) {
System.out.println("Received Data...");
System.out.println("Input received: " + code);
return;
}
}
}
Client.java: This is the Client
public class Client {
public static Socket socket = new Socket();
private int loops = 0;
private int maxLoops = 10;
private static boolean killThread = false;
private String ip;
private int port;
public Client(String receivedIp, String receivedPort) {
ip = receivedIp;
port = Integer.parseInt(receivedPort);
try {
System.out.println("Trying to connect to Server...");
socket.connect(new InetSocketAddress(ip, port));
System.out.println("Connected!");
} catch (IOException e) {
System.out.println("Error occurred while trying to connect to Server.");
}
loopWaitForData();
}
public static void main(String[] args) {
#SuppressWarnings("unused")
Client objClient = new Client("localhost", "22222");
}
public void loopWaitForData() {
while (!killThread) {
System.out.println(maxLoops + ", " + loops);
if (maxLoops - loops > 0) {
try {
waitForData();
} catch (IOException | ClassNotFoundException e) {
loops = loops + 1;
try {
Thread.sleep(2000);
} catch (InterruptedException e1) {
}
System.out.println("Error occurred while waiting for Data. Waiting for more Data. " + Thread.currentThread());
e.printStackTrace();
loopWaitForData();
}
} else if (maxLoops - loops == 0){
System.out.println("Error occurred while waiting for Data. Maximum trys reached. Disbanding connection. " + Thread.currentThread());
try {
socket.close();
} catch (IOException e) {
System.out.println("Failed to close Socket " + Thread.currentThread());
}
loops = loops + 1;
} else {
System.out.println("Closing Thread..." + Thread.currentThread());
killThread = true;
}
}
}
public void waitForData() throws IOException, ClassNotFoundException {
InputStream input = socket.getInputStream();
ObjectInputStream inputObject = new ObjectInputStream(input);
String code;
System.out.println("Waiting for Data...");
while ((code = (String) inputObject.readObject()) != null) {
System.out.println("Received Data...");
System.out.println("Input received: " + code);
answer();
return;
}
}
private void answer() {
try {
String code = new String("1");
ObjectOutputStream outputObject = new ObjectOutputStream(socket.getOutputStream());
outputObject.writeObject(code);
} catch (IOException e) {
System.out.println("Error occurred while trying to answer: " + e + " in " + Thread.currentThread());
}
}
}

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.

How does TCP connection works on Android?

I am using smack for building a chat app in Android. I am using a sticky_service to hold the connection. I have a confusion that if my app goes to sleep what happens to TCP connection. I have read few answers on the page - How to make the Android device hold a TCP connection to Internet without wake lock?
It wakes up for a brief period of time - For smack I can think of it as the processmessage listener (http://www.programcreek.com/java-api-examples/index.php?api=org.jivesoftware.smack.MessageListener) is called. I am inserting data in db for that. Is there any guarantee that work will be complete or if the execution is left in between will it be started from there.
Hello dear you can use this code snippet :
protected void connect() {
Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": connecting");
features.encryptionEnabled = false;
lastConnect = SystemClock.elapsedRealtime();
lastPingSent = SystemClock.elapsedRealtime();
this.attempt++;
try {
shouldAuthenticate = shouldBind = !account.isOptionSet(Account.OPTION_REGISTER);
tagReader = new XmlReader(wakeLock);
tagWriter = new TagWriter();
packetCallbacks.clear();
this.changeStatus(Account.State.CONNECTING);
final Bundle result = DNSHelper.getSRVRecord(account.getServer());
final ArrayList<Parcelable> values = result.getParcelableArrayList("values");
if ("timeout".equals(result.getString("error"))) {
throw new IOException("timeout in dns");
} else if (values != null) {
int i = 0;
boolean socketError = true;
while (socketError && values.size() > i) {
final Bundle namePort = (Bundle) values.get(i);
try {
String srvRecordServer;
try {
srvRecordServer = IDN.toASCII(namePort.getString("name"));
} catch (final IllegalArgumentException e) {
// TODO: Handle me?`
srvRecordServer = "";
}
final int srvRecordPort = namePort.getInt("port");
final String srvIpServer = namePort.getString("ip");
final InetSocketAddress addr;
if (srvIpServer != null) {
addr = new InetSocketAddress(srvIpServer, srvRecordPort);
Log.d(Config.LOGTAG, account.getJid().toBareJid().toString()
+ ": using values from dns " + srvRecordServer
+ "[" + srvIpServer + "]:" + srvRecordPort);
} else {
addr = new InetSocketAddress(srvRecordServer, srvRecordPort);
Log.d(Config.LOGTAG, account.getJid().toBareJid().toString()
+ ": using values from dns "
+ srvRecordServer + ":" + srvRecordPort);
}
socket = new Socket();
socket.connect(addr, 20000);
socketError = false;
} catch (final UnknownHostException e) {
Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": " + e.getMessage());
i++;
} catch (final IOException e) {
Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": " + e.getMessage());
i++;
}
}
if (socketError) {
throw new UnknownHostException();
}
} else if (result.containsKey("error")
&& "nosrv".equals(result.getString("error", null))) {
//todo:change here to server.
socket = new Socket(server_ip, server port);
} else {
throw new IOException("timeout in dns");
}
final OutputStream out = socket.getOutputStream();
tagWriter.setOutputStream(out);
final InputStream in = socket.getInputStream();
tagReader.setInputStream(in);
tagWriter.beginDocument();
sendStartStream();
Tag nextTag;
while ((nextTag = tagReader.readTag()) != null) {
if (nextTag.isStart("stream")) {
processStream(nextTag);
break;
} else {
throw new IOException("unknown tag on connect");
}
}
if (socket.isConnected()) {
socket.close();
}
} catch (final UnknownHostException | ConnectException e) {
this.changeStatus(Account.State.SERVER_NOT_FOUND);
} catch (final IOException | XmlPullParserException | NoSuchAlgorithmException e) {
Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": " + e.getMessage());
this.changeStatus(Account.State.OFFLINE);
} finally {
if (wakeLock.isHeld()) {
try {
wakeLock.release();
} catch (final RuntimeException ignored) {
}
}
}
}
enjoy your code:)

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().)

Categories

Resources