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.
Related
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());
}
}
}
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]".
I i am making a server/client but there seems to be a problem. I cannot seem to connect when i click the button.Please help.Not sure what i did wrong.Feel free to edit code to fix it then comment please.I have a connect button,and a send button. I think it has something to do with the highlighted code but it could be anything. I know this isnt very specific but basically heres the code and it doesnt work. I cant connect . please help!
Client
public class chat_client extends javax.swing.JFrame {
String username;
Socket sock;
BufferedReader reader;
PrintWriter writer;
ArrayList<String>userList = new ArrayList();
Boolean isConnected = false;
public chat_client() {
initComponents();
getContentPane().setBackground(Color.white);
this.setIconImage(new ImageIcon(getClass()
.getResource("dogeIcon.jpg")).getImage());
this.setLocationRelativeTo(null);
}
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)){
txtChat.append(data[0] + ":" + data[1] + "\n");
} else if (data[2].equals(connect)){
txtChat.removeAll();
userAdd(data[0]);
} else if (data[2].equals(disconnect)){
userRemove(data[0]);
} else if (data[2].equals(done)){
userList.setText("");
writeUsers();
}
} catch(Exception ex){
}
}
}
public void ListenThread(){
Thread IncomingReader = new Thread(new IncomingReader());
IncomingReader.start();
}
public void userAdd(String data){
userList.add(data);
}
public void userRemove(String data){
txtChat.append(data + " has disconnected \n");
}
public void writeUsers(){
String[] tempList = new String[(userList.size())];
userList.toArray(tempList);
for (String token:tempList){
userList.append(token + "\n");
}
}
public void sendDisconnect(){
String bye = (username + "^ ^Disconnected");
try{
writer.println(bye);
writer.flush();
} catch(Exception e){
txtChat.append("Could Not Send Disconnect Message \n");
}
}
public void Disconnect(){
try{
txtChat.append("Disconnected\n");
sock.close();
} catch(Exception ex){
txtChat.append("Failed to disconnect\n");
}
isConnected = false;
txtUser.setEditable(true);
userList.setText("");
}
(This is the highlighted part where i think the problem is)
***private void connectActionPerformed(java.awt.event.ActionEvent evt) {
if (isConnected == false){
username = txtUser.getText();
txtUser.setEditable(false);
try{
sock = new Socket("localhost", 1023);
InputStreamReader streamreader
= new InputStreamReader(sock.getInputStream());
reader = new BufferedReader(streamreader);
writer = new PrintWriter(sock.getOutputStream());
writer.println(username + "^has connected.^Connect");
writer.flush();
isConnected = true;
} catch(Exception ex){
txtChat.append("Cannot Connect! Try Again\n");
txtUser.setEditable(true);
}
ListenThread();
} else if (isConnected == true){
txtChat.append("You is connected bra\n");
}
}***
(Ends here-the problem/highlighted part)
private void btn_SendActionPerformed(java.awt.event.ActionEvent evt) {
String nothing = "";
if ((txtMsg.getText()).equals(nothing)){
txtMsg.setText("");
txtMsg.requestFocus();
} else {
try{
writer.println(username + "^" + txtMsg.getText() + "^"
+ "Chat");
writer.flush();
} catch (Exception ex){
txtChat.append("Message was not sent\n");
}
txtMsg.setText("");
txtMsg.requestFocus();
}
A couple things:
You're getting a java.net.ConnectionException (see below) because the connection is being refused. This could be because the server you are trying to connect to is not running, the server is not accepting client connections, the server is not accessible by the client, or you are connecting to the wrong port number.
It is generally bad coding practice to catch Exception directly. You want to either catch the most specific exception that ranges across the variety of exceptions that can be thrown (in this case, IOException) or catch each possible one individually, which is the preferred method. Catch the most specific exceptions before the more general ones so that they are not masked by them. Furthermore it is a good idea to use the Throwable class's getMessage() method so that you can figure out the reason for the exception being thrown. For example:
} catch (java.net.ConnectException ex) {
System.err.println("ConnectException: " + ex.getMessage()); // May return "Connection refused", "Connection timed out", "Connection reset", etc.
} catch (java.rmi.UnknownHostException ex) {
System.err.println("UnknownHostException: " + ex.getMessage()); // Returns the name of the host you were attempting to connect to
} catch (...) {
// code here
} catch (java.io.IOException ex) {
System.err.println("IOException: " + ex.getMessage()); // May return a problem with the BufferedReader or InputStreamReader or PrintWriter
}
Of course, the statements in the catch clause can be modified to your liking.
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().)
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().