Server side auto disconnect user connection and array index outofbounds error - java

server will run the array which disconnect user after client press connect button
public void run() {
String message, connect = "Connect", disconnect = "Disconnect", chat = "Chat" ;
String[] data;
try {
while ((message = reader.readLine()) != null) {
outputTextArea.append("Received: " + message + "\n");
data = message.split(":");
for (String token:data) {
outputTextArea.append(token + "\n");
}
if (data[2].equals(connect)) {
tellEveryone((data[0] + ":" + data[1] + ":" + chat));
userAdd(data[0]);
} else if (data[2].equals(disconnect)) {
tellEveryone((data[0] + ":has disconnected." + ":" + chat));
userRemove(data[0]);
} else if (data[2].equals(chat)) {
tellEveryone(message);
} else {
outputTextArea.append("No Conditions were met. \n");
}
} // end while
} // end try
catch (Exception ex) {
outputTextArea.append("Lost a connection. \n");
ex.printStackTrace();
clientOutputStreams.remove(client);
} // end catch
} // end run()
} // end class ClientHandler
public void userAdd (String data) {
String message, add = ": :Connect", done = "Server: :Done", name = data;
outputTextArea.append("Before " + name + " added. \n");
onlineUsers.add(name);
outputTextArea.append("After " + name + " added. \n");
String[] tempList = new String[(onlineUsers.size())];
onlineUsers.toArray(tempList);
for (String token:tempList) {
message = (token + add);
tellEveryone(message);
}
tellEveryone(done);
}
public void userRemove (String data) {
String message, add = ": :Connect", done = "Server: :Done", name = data;
onlineUsers.remove(name);
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) {
// sends message to everyone connected to server
Iterator it = clientOutputStreams.iterator();
while (it.hasNext()) {
try {
PrintWriter writer = (PrintWriter) it.next();
writer.println(message);
writer.flush();
outputTextArea.setCaretPosition(outputTextArea.getDocument().getLength());
} // end try
catch (Exception ex) {
outputTextArea.append("Error telling everyone. \n");
} // end catch
} // end while
} // end tellEveryone()
Client Side:
ArrayList<String> userlist = new ArrayList();
public class IncomingReader implements Runnable{
public void run(){
String stream;
String[] data;
String done = "Done", connect = "connect", disconnect = "Disconnect", chat ="Chat";
try {
while ((stream = reader.readLine()) != null){
data = stream.split("!");
if (data[2].equals(chat)) {
chatTextArea.append(data[0]+":"+ data[1]+"\n");
chatTextArea.setCaretPosition(chatTextArea.getDocument().getLength());
} else if (data[2].equals(connect)){
chatTextArea.removeAll();
userAdd(data[0]);
} else if (data[2].equals(disconnect)){
userRemove(data[0]);
} else if (data[2].equals(done)){
onlineuserlist.setText("");
writeUsers();
userlist.clear();
}
}
}catch(Exception ex){
}
}
}
private void userAdd(String data) {
userlist.add(data);
}
private void userRemove(String data) {
chatTextArea.append(data +"has disconnected.\n");
}
private void writeUsers() {
String[] tempList = new String[(userlist.size())];
userlist.toArray(tempList);
for (String token:tempList) {
onlineuserlist.append(token +"\n");
}
}
public void sendDisconnect(){
String bye =(username + ": :Disconnect");
try{
writer.println(bye);
writer.flush();
} catch (Exception ex){
chatTextArea.append("could not send Disconnect Message.\n");
}
}
public void Disconnect(){
try{
chatTextArea.append("Disconnected.\n");
sock.close();
} catch (Exception ex){
chatTextArea.append("Failed to disconnect. \n");
}
isConnected = false;
usernameField.setEditable(true);
onlineuserlist.setText("");
}
}
after start the server and client press the connect button, it will show which user has connected but it also disconnect the connection and got this error.
java.lang.ArrayIndexOutOfBoundsException: 2
at chatsystemserver.ServerSide$ClientHandler.run(ServerSide.java:55)
at java.lang.Thread.run(Thread.java:745)

It would appear that you don't have an array of size == 3 when you do you split. You might want to do some array size checking before you access "data[2]".

Related

Using JavaOsc to get meter readings from a Behringer X32

I am trying to work with JavaOsc but I am having difficulties establishing a connection. My test code is below, but it does not matter what IP address port I put in, it appears to connect (which is not correct) and there is no response I am receiving. So I am doing something wrong, but find it hard to find documentation.
final static private int port = 10023;
final static private String ipAddess = "192.168.1.78";
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while(true) {
OSCPortOut sender = null;
OSCPortIn receiver = null;
try {
//receiver = new OSCPortIn(10023);
OSCMessageListener msgListener = new OSCMessageListener() {
#Override
public void acceptMessage(OSCMessageEvent oscMessageEvent) {
System.out.println("Message received A! " + oscMessageEvent.toString());
}
};
OSCPacketListener listener = new OSCPacketListener() {
#Override
public void handlePacket(OSCPacketEvent oscPacketEvent) {
System.out.println("Package received A! " + oscPacketEvent.toString());
}
#Override
public void handleBadData(OSCBadDataEvent oscBadDataEvent) {
System.out.println("Package BAD received B!");
}
public void acceptMessage(java.util.Date time, OSCMessage message) {
System.out.println("Message received!");
}
};
MessageSelector selector = new MessageSelector() {
#Override
public boolean isInfoRequired() {
System.out.println("Info required call");
return false;
}
#Override
public boolean matches(OSCMessageEvent oscMessageEvent) {
System.out.println("Message match?? " + oscMessageEvent.toString());
return false;
}
};
receiver = new OSCPortInBuilder().addPacketListener(listener).addMessageListener(selector, msgListener).setLocalPort(port).setRemotePort(port).build();
receiver.connect();
receiver.startListening();
sender = new OSCPortOut(InetAddress.getByName(ipAddess), port);
sender.connect();
System.out.println("Remote address: " + sender.getRemoteAddress() + " local: " + sender.getLocalAddress());
List<String> vars = new ArrayList<String>();
vars.add("/info");
OSCMessage msg = new OSCMessage("/msgAddress", vars);
System.out.println("Is connected: " + sender.isConnected());
sender.send(msg);
System.out.println("Msg info: " + msg.getInfo() + " - " + msg.getAddress());
System.out.println("Deamon: " + receiver.isDaemonListener() + " is listening " + receiver.isListening() + " is connected " + receiver.isConnected());
System.out.println("Please type 'q' to stop.");
if(scanner.nextLine().equalsIgnoreCase("q")) break;
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
e.printStackTrace(System.out);
} finally {
try {
if (sender != null) sender.close();
if (receiver != null) receiver.close();
} catch (IOException e){
System.out.println("Problem closing: " + e.getMessage());
}
}
}
System.out.println("Finished.");
The response is:
Info required
Remote address: /192.168.1.78:10023 local: /0.0.0.0:0
Is connected: true
Msg info: null - /msgAddress
Deamon: true is listening true is connected true
Please type 'q' to stop.
I also tried to contact the local receiver (using 127.0.0.1) but that didn't work either.
Any suggestions would be really appreciated!

Simple java bot telegram: messages in loop

I'm trying to make simple telegram bot on Java.
The question is: how can I receive messages in a loop, when the user typed /start? I have already some
#Override
public void onUpdateReceived(Update update) {
Message msg = update.getMessage();
String txt = msg.getText();
if (txt.equals("/start")) {
sendMsg(msg, "Привет, меня зовут бот " + name + "!");
showHelp(msg);
run(msg, update);
} else if (txt.equals("/help")) {
showHelp(msg);
}
}
Here's showhelp:
private void showHelp(Message msg) {
try {
String inAbout = ReadFile.readFileInString(this.about);
sendMsg(msg, inAbout);
} catch (Exception ex) {
ex.printStackTrace();
}
}
sendMsg:
private void sendMsg(Message msg, String text) {
SendMessage s = new SendMessage();
s.setChatId(msg.getChatId());
s.setText(text);
try {
execute(s);
} catch (TelegramApiException e) {
e.printStackTrace();
}
}
In Run I want to read questions from data and wait for users answer, check if correct and do it in loop. In the end show how many he answered correct.
public void run(Message msg, Update update) {
try {
List<String> data = ReadFile.readFileInList(this.getData());
List<String> dataAnswers = ReadFile.readFileInList(this.answers);
this.sizeOfAnswers = data.size();
for (int i = 0; i < data.size(); i++) {
String line = data.get(i);
sendMsg(msg, line);
String inAnswer = update.getMessage().getText();
String rAns = dataAnswers.get(i);
boolean flag = checkAnswer(inAnswer, rAns);
if (flag) {
this.currentUser.incrementScore();
}
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
String finalString = "Поздравляю, ты ответил на " + this.currentUser.getScore() + "/" + this.sizeOfAnswers
+ " вопросов!";
sendMsg(msg, finalString);
}
}
Also here is maybe some multi user problems. How should I do it? Now it's showing all questions in one second without waiting for an answer.
How it's working now

How to remove names from list in all clients in Client/Server chat program

I am working on Client/Server chat and am having issues removing the name from the list on all the open clients when one client disconnects. Right I have it where it seems like it broadcasting the list between the clients but its not removing any of the name. Any help would be awesome. This project is worth 50% of my final grade.
Chat Server Code:
class ChatHandler extends Thread
{ public ChatHandler(Socket i, ArrayList<ChatHandler> h)
{
incoming = i;
handlers = h;
handlers.add(this);
try{
in = new ObjectInputStream(incoming.getInputStream());
out = new ObjectOutputStream(incoming.getOutputStream());
}catch(IOException ioe){
System.out.println("Could not create streams.");
}
}
public synchronized void broadcast(){
ChatHandler left = null;
for(ChatHandler handler : handlers){
ChatMessage cm = new ChatMessage();
cm.setMessage(myObject.getMessage());
cm.setName(myObject.getName());
try{
handler.out.writeObject(cm);
System.out.println("Writing to handler outputstream: " + cm.getMessage());
}catch(IOException ioe){
//one of the other handlers hung up
left = handler; // remove that handler from the arraylist
}
}
handlers.remove(left);
if(myObject.getMessage().equals("bye")){ // my client wants to leave
done = true;
handlers.remove(this);
System.out.println("Removed handler. Number of handlers: " + handlers.size());
}
System.out.println("Number of handlers: " + handlers.size());
}
public void run()
{
try{
while(!done){
myObject = (ChatMessage)in.readObject();
System.out.println("Message read: " + myObject.getMessage());
broadcast();
}
} catch (IOException e){
if(e.getMessage().equals("Connection reset")){
System.out.println("A client terminated its connection.");
}else{
System.out.println("Problem receiving: " + e.getMessage());
}
}catch(ClassNotFoundException cnfe){
System.out.println(cnfe.getMessage());
}finally{
handlers.remove(this);
}
}
Client Code:
public void actionPerformed(ActionEvent ae){
//TF ACTION LISTENER
if (ae.getSource()== tf){
if (connected) {
myObject = new ChatMessage();
myObject.setMessage(tf.getText());
myObject.setName(name);
tf.setText("");
try{
myOutputStream.reset();
myOutputStream.writeObject(myObject);
}catch(IOException ioe){
System.out.println(ioe.getMessage());
}
}else{
name = tf.getText();
setName(name);
}
}
//BUTTONS
if (ae.getSource()== connect){
connected = true;
name = tf.getText();
setName(name);
try{
scan = new Scanner(System.in);
myObject = new ChatMessage();
socketToServer = new Socket("127.0.0.1", 4001);
myOutputStream = new ObjectOutputStream(socketToServer.getOutputStream());
myInputStream = new ObjectInputStream(socketToServer.getInputStream());
start();
}
catch(Exception e){
System.out.println(e.getMessage());
}
name = tf.getText();
setName(name);
myObject = new ChatMessage();
myObject.setMessage(getName() + " has connected");
myObject.setName(name);
tf.setText("");
try{
myOutputStream.reset();
myOutputStream.writeObject(myObject);
}catch(IOException ioe){
System.out.println(ioe.getMessage());
}
disconnect.setEnabled(true);
}
if(ae.getSource()== disconnect){
connected = false;
myObject = new ChatMessage();
myObject.setMessage(getName() + " has disconnected");
myObject.setName(name);
myObject.setRemoveName(Clientlist);
tf.setText("");
try{
myOutputStream.reset();
myOutputStream.writeObject(myObject);
}catch(IOException ioe){
System.out.println(ioe.getMessage());
}
/*
String[] items = Clientlist.getItems();
for (String s: items){
if(s.equals(myObject.getName())){
RemoveFrom = true;
}
}
if(RemoveFrom == true){
Clientlist.remove(myObject.getName());
}*/
try{
myObject.setRemoveName(Clientlist);
socketToServer.close();
myOutputStream.close();
myInputStream.close();
}catch(IOException ioe){
System.out.println(ioe.getMessage());
}
}
}
public void run(){
System.out.println("Listening for messages from server . . . ");
try{
while(!receivingdone){
myObject = (ChatMessage)myInputStream.readObject();
ta.append(myObject.getName() + ": " + myObject.getMessage() + "\n");
String[] items = Clientlist.getItems();
boolean inList = false;
for (String s : items){
if (s.equals(myObject.getName()))
{ inList = true; }
}
if (inList == false) {
Clientlist.add(myObject.getName());
}
if (connected == false){
for (String s: items){
if(s.equals(myObject.getName())){
RemoveFrom = true;
}
}
if(RemoveFrom == true){
Clientlist.remove(myObject.getName());
}
}
}
}catch(IOException ioe){
System.out.println("IOE: " + ioe.getMessage());
}catch(ClassNotFoundException cnf){
System.out.println(cnf.getMessage());
}
}
Chat Message Code:
import java.io.*;
import java.awt.*;
public class ChatMessage implements Serializable{
public String name;
public String message;
public List list;
public ChatMessage(){}
public ChatMessage(String name, String message){
setName(name);
setMessage(message);
setRemoveName(list);
}
public void setName(String name){
this.name = name;
}
public String getName(){
return name;
}
public void setMessage(String message){
this.message = message;
}
public String getMessage(){
return message;
}
public void setRemoveName(List list){
list.remove(getName());
this.list = list;
}
public List getRemoveName(){
return list;
}
}

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