Socket gets Closed after 1st command - java

am making a simple ftp client/server program which on command from the clients lists files, tells the current directory, downloads files.
I want to create a server which is able to be connect with multiple clients and is capable of handling multiple commands at a time. I have used threading but my code gives the following error after the 1st command is executed.
socket closed
at java.net.SocketInputStream.socketRead0(Native Method)
at java.net.SocketInputStream.read(Unknown Source)
at java.net.SocketInputStream.read(Unknown Source)
at java.io.DataInputStream.read(Unknown Source)
at sun.nio.cs.StreamDecoder.readBytes(Unknown Source)
at sun.nio.cs.StreamDecoder.implRead(Unknown Source)
at sun.nio.cs.StreamDecoder.read(Unknown Source)
at java.io.InputStreamReader.read(Unknown Source)
at java.io.BufferedReader.fill(Unknown Source)
at java.io.BufferedReader.readLine(Unknown Source)
at java.io.BufferedReader.readLine(Unknown Source)
at Myserver$Connecthandle.run(Myserver.java:123)
at Myserver.main(Myserver.java:35)
java.net.SocketException: socket closed
Here's my server code:
public class Myserver {
static final int PortNumber = 120;
static ServerSocket MyService;
static Socket clientSocket = null;
/**
* #param args
* #throws IOException
*/
public static void main(String[] args) throws IOException {
File directory;
directory = new File(System.getProperty("user.dir"));
try {
MyService = new ServerSocket(PortNumber);
String cd = directory.toString();
System.out.println(cd);
System.out.println("Listening on " + PortNumber);
while(true) {
clientSocket = MyService.accept();
Connecthandle a = new Connecthandle(clientSocket, directory);
a.start();
}
}
catch (IOException e) {
System.out.println(e);
}
}
static class Connecthandle extends Thread {
File Directory;
Socket clientsocket;
PrintWriter outgoing;
// Constructor for class
Connecthandle(Socket clients, File dir) {
clientsocket = clients;
Directory = dir;
}
// Works Fine
void listfiles() throws IOException {
String []Listfile = Directory.list();
String send = "";
for (int j = 0; j < Listfile.length; j++) {
send = send + Listfile[j] + ",";
}
DataOutputStream GoingOut = new DataOutputStream(clientsocket.getOutputStream());
GoingOut.writeBytes(send);
GoingOut.flush();
// GoingOut.close();
}
// Works Fine
void currentdirectory() throws IOException {
String cd = Directory.toString();
String cdd = "resp," + cd;
System.out.println(cdd);
DataOutputStream GoingOut = new DataOutputStream(clientsocket.getOutputStream());
GoingOut.writeBytes(cdd);
GoingOut.flush();
GoingOut.close();
}
// Works fine
void sendfiles(String fileName) {
try {
File nfile = new File(fileName);
DataOutputStream GoingOut = new DataOutputStream(clientsocket.getOutputStream());
if ( (! nfile.exists()) || nfile.isDirectory() ) {
GoingOut.writeBytes("file not present");
} else {
BufferedReader br = new BufferedReader(new FileReader(nfile));
int coun = 0;
String lin;
while ((lin = br.readLine()) != null) {
coun++;
}
GoingOut.writeBytes("resp," + fileName + "," + String.valueOf(coun) + "\n");
#SuppressWarnings("resource")
BufferedReader sr = new BufferedReader(new FileReader(nfile));
String line;
while ((line = sr.readLine()) != null) {
GoingOut.writeBytes(line+"\n");
GoingOut.flush();
}
GoingOut.close();
br.close();
}
} catch (IOException e) {
System.out.println("Unable to send!");
}
}
public void start() {
DataInputStream comingin = null;
try {
comingin = new DataInputStream(clientsocket.getInputStream());
} catch (IOException e2) {
e2.printStackTrace();
}
InputStreamReader isr = null;
try {
isr = new InputStreamReader(comingin, "UTF-8");
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
BufferedReader br = new BufferedReader(isr);
while (true) {
try {
String message = br.readLine();
if (message.contains("pwd")) {
currentdirectory();
} else if (message.contains("list")) {
listfiles();
} else if (message.contains("get")) {
String fileName = new String(message.substring(8, message.length()));
sendfiles(fileName);
} else if (message.contains("exit")) {
System.exit(0);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
clientsocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
}
I moved all the methods into start() so i only needed to declare dataoutputstream once but now it gives a NULLPOINTEREXCEPTION whenever i use Outgoing.writeBytes
Updated:
static class Connecthandle extends Thread {
File Directory;
Socket clientsocket;
PrintWriter outgoing;
// Constructor for class
Connecthandle(Socket clients, File dir) {
clientsocket = clients;
Directory = dir;
}
public void run() {
DataInputStream comingin = null;
try {
comingin = new DataInputStream(clientsocket.getInputStream());
} catch (IOException e2) {
e2.printStackTrace();
}
InputStreamReader isr = null;
try {
isr = new InputStreamReader(comingin, "UTF-8");
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
BufferedReader br = new BufferedReader(isr);
while (true) {
try {
String message = br.readLine();
if (message.contains("pwd")) {
String cd = Directory.toString();
String cdd = "resp," + cd;
System.out.println(cdd);
DataOutputStream GoingOut = new DataOutputStream(clientsocket.getOutputStream());
GoingOut.writeBytes(cdd);
GoingOut.flush();
} else if (message.contains("list")) {
String []Listfile = Directory.list();
String send = "";
for (int j = 0; j < Listfile.length; j++) {
send = send + Listfile[j] + ",";
}
DataOutputStream GoingOut = new DataOutputStream(clientsocket.getOutputStream());
GoingOut.writeBytes(send);
GoingOut.flush();
} else if (message.contains("get")) {
String fileName = new String(message.substring(8, message.length()));
try {
File nfile = new File(fileName);
DataOutputStream GoingOut = new DataOutputStream(clientsocket.getOutputStream());
if ( (! nfile.exists()) || nfile.isDirectory() ) {
GoingOut.writeBytes("file not present");
} else {
BufferedReader wr = new BufferedReader(new FileReader(nfile));
int coun = 0;
String lin;
while ((lin = wr.readLine()) != null) {
coun++;
}
GoingOut.writeBytes("resp," + fileName + "," + String.valueOf(coun) + "\n");
#SuppressWarnings("resource")
BufferedReader sr = new BufferedReader(new FileReader(nfile));
String line;
while ((line = sr.readLine()) != null) {
GoingOut.writeBytes(line+"\n");
GoingOut.flush();
}
GoingOut.close();
br.close();
}
} catch (IOException e) {
System.out.println("Unable to send!");
}
} else if (message.contains("exit")) {
System.exit(0);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
clientsocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
}

Closing the input stream or output stream of a socket closes the other stream and the socket. I don't see why you need to close anything here until the client disconnects or you time him out.

Related

readline() method of bufferedreader(socket.getinputstream) not waiting for input from client

I'm developing an E-voting system using java. The client sends a number that represents a requested method. The run() method of the server thread then waits for input from the socket according to the sent number. The server reads input normally for the first client request however i get the following exception from the server:
Exception in thread "Thread-0" java.lang.NumberFormatException: For
input string: "test" at
java.lang.NumberFormatException.forInputString(Unknown Source) at
java.lang.Integer.parseInt(Unknown Source) at
java.lang.Integer.parseInt(Unknown Source) at
ServerThread.run(ServerThread.java:139)
Then the thread is terminated abnormally (i concluded that because when i try to perform another operation from the same client GUI i get a SocketException: Socket is closed). The user = Integer.parseInt(in.readLine()); should wait for another integer to be sent by the client but its not. Its reading the last string sent. (Im using BufferedReader)
here is the run method of the serverthread:
public void run() {
while (true) {
int user = -1;
// while ((user = Integer.parseInt(in.readLine())) != -1) {
try {
user = Integer.parseInt(in.readLine());
} catch (IOException e) {
System.out.println("Command Error");
}
switch (user) {
case 1:
try {
String username = in.readLine();
String password = in.readLine();
int cid = -1;
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(
"SELECT UUID FROM user_acc WHERE UUID IN (SELECT CID FROM candidate) AND username = '"
+ username + "';");
if (Security.Authenticate(username, password) && !username.equals("") && !password.equals(""))
out.println("true");
else {
out.println("false");
// in.reset();
break;
}
if (rs.next()) {
cid = rs.getInt(1);
String inetAddress = clientSocket.getInetAddress().toString().substring(1);
stmt.executeUpdate(
"UPDATE candidate SET ipadd = '" + inetAddress + "' WHERE CID = " + cid + ";");
}
} catch (IOException e) {
System.out.println("Writing in Sign in Error");
} catch (UserNotExistingException e) {
} catch (SQLException e) {
e.printStackTrace();
}
break;
case 2:
try {
String username = in.readLine();
String name = in.readLine();
String password = in.readLine();
String email = in.readLine();
String conf = in.readLine();
if (Security.signUp(username, name, email, password, conf))
out.println("true");
else
out.println("false");
} catch (IOException e) {
System.out.println("Reading in Sign Up Error");
} catch (UsernameEmailExistsException e) {
System.out.println("Email Exists");
out.println("false");
}
break;
case 3:
try {
String email = in.readLine();
String code;
if (Security.forgotPass(email)) {
out.println("true");
code = in.readLine();
} else {
out.println("false");
break;
}
if (Security.checkCode(code, email))
out.println("true");
else {
out.println("false");
break;
}
String newpass = in.readLine();
String conf = in.readLine();
String username = "";
for (int i = 0; i < email.length(); i++)
if (email.charAt(i) == '#')
break;
else
username += email.charAt(i);
if (Security.forceChangePassword(username, newpass, conf)) {
out.println("true");
} else
out.println("false");
} catch (IOException e) {
System.out.println("Reading in Forget Pass Error");
}
break;
case 4:
try {
int CID = Integer.parseInt(in.readLine()), userID = Integer.parseInt(in.readLine());
try {
if (nominate(CID, userID))
out.println("true");
else
out.println("false");
} catch (ClassNotFoundException | SQLException | UserNotExistingException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
break;
case 5:
try {
int uid = Integer.parseInt(in.readLine());
String candname = in.readLine();
if (vote(candname, uid))
out.println("true");
else
out.println("false");
} catch (IOException e) {
e.printStackTrace();
}
break;
case 6:
break;
case 7:
try {
String text = in.readLine();
int UID = Integer.parseInt(in.readLine());
int CID = Integer.parseInt(in.readLine());
if (postComment(text, UID, CID))
out.println("true");
else
out.println("false");
} catch (IOException e) {
e.printStackTrace();
}
break;
case 10:
try {
String username = in.readLine();
String oldPass = in.readLine();
String newPass = in.readLine();
String conf = in.readLine();
if (Security.changePass(username, oldPass, newPass, conf))
out.println("true");
else
out.println("false");
} catch (IOException e) {
e.printStackTrace();
}
break;
case 11:
try {
int CID = Integer.parseInt(in.readLine());
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT ipadd FROM candidate WHERE CID = " + CID + ";");
if (rs.next())
out.println(rs.getString(1));
int port = Integer.parseInt(in.readLine());
out.write(port);
} catch (IOException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
break;
}
}
}
Here are my Client methods (in case the problem lies in them):
public class Client {
private static Socket clientSocket;
private final int PORT_NUM = 4373;
private static DataOutputStream p2pout;
private String IP;
public Client(String IP) throws IOException {
this.IP = IP;
try {
clientSocket = new Socket(IP, PORT_NUM);
} catch (Exception e) {
System.err.println("Cannot connect to the server, try again later.");
System.exit(1);
}
}
public void sendCommand(int com) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
out.println(com + "");
out.close();
in.close();
}
public static boolean SignIn(String Username, String password) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
out.println(1);
out.println(Username);
out.println(password + "\n");
String reply = in.readLine();
out.close();
in.close();
if (reply.equals("true"))
return true;
else
return false;
}
public static boolean SignUp(String Username, String name, String email, String password, String conf)
throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
out.println(2);
out.println(Username);
out.println(name);
out.println(password);
out.println(email);
out.println(conf);
String reply = in.readLine();
out.close();
in.close();
if (reply.equals("true"))
return true;
else
return false;
}
public static boolean ForgetPass(String email) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
out.println(3);
out.println(email);
String reply = in.readLine();
if (reply.equals("true"))
return true;
else
return false;
}
public static boolean ForgetPass2(String code) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
out.println(3);
out.println(code);
String reply = in.readLine();
if (reply.equals("true"))
return true;
else
return false;
}
public static boolean ForgetPass3(String newpass, String conf) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
out.println(newpass);
out.println(conf);
String reply = in.readLine();
out.close();
in.close();
if (reply.equals("true"))
return true;
else
return false;
}
public static boolean nominate(int CID, int UserID) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
out.println(4);
out.println(CID + "");
out.println(UserID + "");
String reply = in.readLine();
out.close();
in.close();
if (reply.equals("true"))
return true;
else
return false;
}
public static boolean vote(int cid, int UID) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
out.println(5);
out.println(cid);
out.println("" + UID);
String reply = in.readLine();
out.close();
in.close();
if (reply.equals("true"))
return true;
else
return false;
}
public static boolean postcomment(int CID, String text, int UID) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
out.println(7);
out.println(text + "");
out.println(UID + "");
out.println(CID + "");
String reply = in.readLine();
out.close();
in.close();
if (reply.equals("true"))
return true;
else
return false;
}
public static boolean Changepass(String Username, String oldpass, String newpass, String conf) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
out.println(10);
out.println(Username);
out.println(oldpass);
out.println(newpass);
out.println(conf);
String reply = in.readLine();
out.close();
in.close();
if (reply.equals("true"))
return true;
else
return false;
}
public String getIPAddress(int cid) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
out.println(11);
out.println(cid + "");
String inetAddress = in.readLine();
out.close();
in.close();
return inetAddress;
}
public int getServerChatPort() throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
int port = Integer.parseInt(in.readLine());
out.close();
in.close();
return port;
}
public static void connectionListener(String inetadd) {
try {
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
ServerSocket ss = new ServerSocket(0);
Socket clientSocket = ss.accept();
out.println(ss.getLocalPort() + "");
Socket candSock = ss.accept();
ChatListener cl = new ChatListener(candSock);
cl.start();
out.close();
in.close();
while (true) {
if (ChatListener.flag == 1)
cl.display();
// ^^ Displayed in GUI
}
} catch (IOException e) {
e.printStackTrace();
}
}
public Socket chatConnect(String inetAdd) {
Socket soc = null;
try {
int port = getServerChatPort();
soc = new Socket(inetAdd, port);
} catch (IOException e) {
e.printStackTrace();
}
return soc;
}
public void send(String m) {
try {
p2pout.writeChars(m);
} catch (IOException e) {
e.printStackTrace();
}
}
public void close() throws IOException {
clientSocket.close();
}
}
The root of problem is the socket close after each operation. Well the code close the output stream connected to the socket but closing the stream returned from getOutputStream() closes the associated socket as well.
The subsequent client send attempt fails because the socket is closed and the server fails because the receive operation (readLine()) is interrupted and no data is received.
Try to keep the client output stream open. You can create an class attribute like for Socket or whatever.

Socket server stuck

I'm trying to make a server/client to send text from client to server then sending back an ok message or something similar back to the client, but for some error that I can't see, either the server gets stuck right before sending the ok back to the client, or the client does not receive the message (I think it's the first one though).
Any help is appreciated.
This is the server code:
class ActiveServer extends Thread {
InputStream inStream;
OutputStream outStream;
public ActiveServer(InputStream inStream, OutputStream outStream) {
this.inStream = inStream;
this.outStream = outStream;
}
#Override
public void run() {
boolean ret = false;
try (BufferedReader reader = new BufferedReader(new InputStreamReader(inStream));
PrintWriter writer = new PrintWriter(outStream);) {
String line = null;
while((line = reader.readLine()) != null) {
String[] str = line.split(";");
line = null;
switch (str[0]) {
case "insert" : //ret = SQLOptions.insert(str[1], str[2]);
System.out.println(str[1]);
break;
}
writer.print(ret);
writer.flush();
// As far as i can see it gets stuck at the end of this while, but I don't know why.
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public class Server {
private static final int PORT = 39165;
public static void main(String[] args) {
try (ServerSocket server = new ServerSocket(PORT);) {
System.out.println("Servidor online");
ExecutorService service = Executors.newFixedThreadPool(10);
while (true) {
Socket client = server.accept();
InetAddress ip = client.getInetAddress();
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
Date time = new Date();
System.out.print(sdf.format(time));
System.out.println(" " + ip + " connected");
InputStream inStream = client.getInputStream();
OutputStream outStream = client.getOutputStream();
service.execute(new ActiveServer(inStream,outStream));
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
And here goes the client code:
public class Telnet {
static Console console = System.console();
public static void connect(String ip, String port) {
try(Socket socket = new Socket(ip, Integer.parseInt(port));
PrintWriter writer = new PrintWriter(socket.getOutputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));) {
String msg = null;
while(true) {
msg = console.readLine();
writer.println(msg);
writer.flush();
if (msg.equals(".quit")) {
System.out.println("Exiting...");
break;
}
String input = reader.readLine();
System.out.println(input);
}
} catch (NumberFormatException e) {
e.printStackTrace();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
if(args.length < 2) {
err.println("Telnet <ip> <port>");
return;
}
if (console == null) {
err.println("A console is not available");
return;
}
connect(args[0], args[1]);
}
}
On the server side, you write the response without a terminating newline:
writer.print(ret);
But on the client side, you read until the end of line:
String input = reader.readLine();
The documentation for BufferedReader#readLine says:
Reads a line of text. A line is considered to be terminated by any one of a line feed ('\n'), a carriage return ('\r'), or a carriage return followed immediately by a linefeed.
Thus, the client will wait forever for the newline sequence which the server will never send.

socket hangs after idle time :server - client java program

Hi i have written a server program to receive ISO8583-93 version requests process them and send response.I will be receiving continuous requests.It works fine ,but if socket is idle when the next request comes, server is not reading.
Please find below code snippet
SERVER :
public class MBServ {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = null;
boolean listening = true;
String request_date = null;
String request_time = null;
try {
serverSocket = new ServerSocket(7777);
} catch (IOException e) {
System.err.println("Could not listen on port: 7777.");
System.exit(-1);
}
while (listening) {
new MBServT(serverSocket.accept()).start();
}
serverSocket.close();
}
}
THREAD:
public class MBServT extends Thread {
private Socket socket = null;
Logger log = Logger.getLogger(MBServT .class.getName());
public MBServT(Socket socket) throws FileNotFoundException, IOException {
super("MBServT");
this.socket = socket;
}
public void run() {
String inputLine = "";
String msgType = null;
int response = 12;
String outwardMsg = null;
BufferedReader buffReaderObj = null;
// String ip = "172.30.12.69";
String stanNo = "0";
boolean ISSUBFIELDPARSING = false;
GenericPackager packager;
try {
packager = new GenericPackager("basicparse.xml");
BufferedReader is = new BufferedReader(new InputStreamReader(socket
.getInputStream(), "ISO8859_1"));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
socket.getOutputStream(), "ISO8859_1"));
String strBuf = null;
int length = 4;
char[] chrBuf = new char[length];
int cnt = 0;
while (true) {
socket.setKeepAlive(true);
int value = 0;
int ret = 0;
ret = is.read(chrBuf, 0, chrBuf.length);
if (-1 == ret)
{
log.error("nothing to read closing socket");
try{
socket.close();
}
catch(Exception e){
System.out.println("Error in socket.close: " +e.toString());
}
throw new Exception("Read Error: Socket closed");
}
strBuf = new String(chrBuf);
chrBuf = new char[Integer.parseInt(strBuf)];
is.read(chrBuf, 0, chrBuf.length);
strBuf = new String(chrBuf);
chrBuf = null;
chrBuf = new char[4];
value = 0;
/*writing response*/
Runnable respThread = new MBServRespT(writer, fieldList,
"threadname");
((Thread) respThread).start();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("Error::" + e.toString());
} finally {
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
It worked after we implemented set sockettimeout.

How to react to events while blocked by input java

I have Socket- Client application. The code below is supposed to allow client to both read replies from server and read input at the same time. The thing is- this code "works" while debugging in eclipse, as in I recieve messages outside of normal flow in a process I'm debugging, but If i launch application normally, it completly ignores that proces? What is the most common cause of "IDE working, real life not" syndrome?
Whole files:
Server:
public class Server implements Runnable {
static ServerSocket serverSocket;
Socket tempSocket;
Socket tempSocket2;
static volatile List<User> usersList = new ArrayList<User>();
static boolean waitForNew = true;
PrintWriter tempOut;
volatile User[] tempUser;
volatile boolean isReadingN = false;
public Server(Socket _s, Socket _s2) {
tempSocket = _s;
tempSocket2 = _s2;
}
public Server(PrintWriter nOut, User[] user) {
tempOut = nOut;
tempUser = user;
isReadingN = true;
}
#Override
public void run() {
if (isReadingN) {
while (true) {
if (tempUser != null && tempUser.length > 0
&& tempUser[0] != null)
break;
}
User[] myUser = new User[1];
myUser[0] = tempUser[0];
// myUser[0]=usersList.
while (true) {
if (myUser[0].isCurrentlyLoggedIn() == false)
break;
String[] toSend = null;
if (myUser[0].isNotificable())
toSend = myUser[0].printNotifications().split("\n");
else
continue;
//tempOut.println("");
int sendL=toSend.length;
tempOut.println(String.valueOf(sendL));
for (int i = 0; i < toSend.length; i++)
tempOut.println(toSend[i]);
}
return;
}
Socket clientSocket = tempSocket;
System.out.println("Initiating conversation with the client");
String inputLine;
try {
System.out.print("creating server out...");
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(),
true);
Socket iClientSocket = tempSocket2;
ObjectOutputStream iout = new ObjectOutputStream(
iClientSocket.getOutputStream());
System.out.println("OK!");
System.out.print("creating server in...");
BufferedReader in = new BufferedReader(new InputStreamReader(
clientSocket.getInputStream()));
System.out.println("OK!");
System.out.print("creating server image streams...");
System.out.println("OK!");
System.out.println("Server initiating conversation");
User[] currentUser = new User[1];
new Thread(new Server(out, currentUser)).start();
while ((inputLine = in.readLine()) != null) {
System.out.println(inputLine);
boolean[] downloadPicture = new boolean[1];
downloadPicture[0] = false;
String input = Command.call(inputLine, currentUser, usersList,
downloadPicture);
String[] toSend;
if (input != null) {
toSend = input.split("\n");
} else
toSend = new String[0];
out.println(String.valueOf(toSend.length));
for (int i = 0; i < toSend.length; i++)
out.println(toSend[i]);
if (downloadPicture[0]) {
System.out.println("File sent.");
iin.close();
} else{
out.println("1");
out.println("Error: File does not exit.");}
} else
//out.println(" ");
if (inputLine.equals("EXIT")) {
waitForNew = false;
break;
}
}
// End communication graciously
System.out.println("Closing sockets, closing streams");
out.close();
in.close();
clientSocket.close();
serverSocket.close();
} catch (IIOException e) {
System.out.println("Error: Could not find file");
e.printStackTrace();
System.exit(-1);
} catch (IOException e) {
System.out.println("Error");
e.printStackTrace();
System.exit(-1);
}
}
public static void main(String[] args) {
// Create socket on port given in argument, localhost
if (args.length == 0) {
System.out
.println("Not enough arguments. Try Server <port number>");
System.exit(-1);
}
int port = 0;
try {
port = Integer.valueOf(args[0]);
System.out.println("Application start");
serverSocket = new ServerSocket(port);
System.out.println("Created socket on port " + port);
} catch (NumberFormatException c) {
System.out
.println("Incorrect port number. Try Server <port number>");
System.exit(-1);
} catch (IOException e) {
System.exit(-1);
}
// Waiting for client
System.out.println("Waiting for client...");
Socket clientSocket = null;
Socket iClientSocket = null;
while (waitForNew) {
try {
clientSocket = serverSocket.accept();
iClientSocket = serverSocket.accept();
new Thread(new Server(clientSocket, iClientSocket)).start();
} catch (IOException e) {
System.out.println("Accept failed: " + port);
System.exit(-1);
}
}
}
}
Client:
public class Client implements Runnable {
static Socket clientSocket = null;
static Socket iClientSocket = null;
static PrintWriter out = null;
static BufferedReader in = null;
static InputStream iin = null;
public static void main(String[] args) {
int port = Integer.valueOf(args[1]);
String host = args[0];
try {
clientSocket = new Socket(host, port);
iClientSocket = new Socket(host, port);
out = new PrintWriter(clientSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(
clientSocket.getInputStream()));
iin = iClientSocket.getInputStream();
} catch (UnknownHostException e) {
System.err.println("Don't know about host: " + host);
System.exit(-1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for " + "the connection to: "
+ host);
System.exit(-1);
}
BufferedReader stdIn = new BufferedReader(new InputStreamReader(
System.in));
String userInput;
try {
new Thread(new Client()).start();
while ((userInput = stdIn.readLine()) != null) {
out.println(userInput);
}
System.out.println("Closing sockets, closing streams");
out.close();
in.close();
stdIn.close();
iClientSocket.close();
clientSocket.close();
} catch (IOException e) {
System.exit(-1);
}
}
#Override
public void run() {
String a = null;
try {
while (true) {
if((a = in.readLine()) == null)
continue;
int n;
try{
n = Integer.valueOf(a);
}catch(NumberFormatException e){
System.out.println(a);
n=1;
//continue;
}
a = "";
for (int i = 0; i < n; i++)
a += in.readLine() + "\n";
System.out.println(a);
// if(a.contains("POST"),)
if (a.compareToIgnoreCase("EXIT") == 0) {
System.out.println("Exiting");
break;
}
if (a.endsWith("Sending File\n")) {
System.out.println("Recieving image.");
(some unimportant for now code)
System.out.println("Image recieved");
}
}
} catch (IOException e) {
}
}
}

Java Chat System

I'm having problems with broadcasting the messages sent by each client. The server can receive each message from multiple clients but it cannot broadcast it. Error message says connection refused
Client:
public void initializeConnection(){
try {
host = InetAddress.getLocalHost();
try{
// Create file
FileWriter fstream = new FileWriter("src/out.txt", true);
BufferedWriter out = new BufferedWriter(fstream);
out.write(host.getHostAddress()+'\n');
//Close the output stream
out.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
clientSocket = new Socket(host.getHostAddress(), port);
outToServer = new PrintWriter(clientSocket.getOutputStream(), true);
inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
}
catch(IOException ioEx) {
ioEx.printStackTrace();
}
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==quit){
try {
outToServer.close();
clientSocket.close();
System.exit(1);
} catch (IOException e1) {
e1.printStackTrace();
}
}
else if(e.getSource()==button){
if(outMsgArea.getText()!=null || !outMsgArea.getText().equals("")){
String message = outMsgArea.getText();
outToServer.println(clientName+": "+message);
outMsgArea.setText("");
}
}
}
public void run(){
try {
while(true){
String message = inFromServer.readLine();
System.out.println(message);
inMsgArea.append(message+'\n');
}
} catch (IOException e) {
e.printStackTrace();
}
}
Server:
import java.io.*;
import java.net.*;
import java.util.*;
public class RelayChatServer {
public static int port = 44442;
ServerSocket server;
public void listenSocket(){
try{
server = new ServerSocket(port);
} catch (IOException e) {
System.out.println("Could not listen on port 4444");
System.exit(-1);
}
while(true){
ClientWorker w;
try{
//server.accept returns a client connection
w = new ClientWorker(server.accept());
Thread t = new Thread(w);
t.start();
} catch (IOException e) {
System.out.println("Accept failed: 4444");
System.exit(-1);
}
}
}
protected void finalize(){
//Objects created in run method are finalized when
//program terminates and thread exits
try{
server.close();
} catch (IOException e) {
System.out.println("Could not close socket");
System.exit(-1);
}
}
public static void main(String[] args) {
new RelayChatServer().listenSocket();
}
}
class ClientWorker implements Runnable {
private Socket client;
//Constructor
ClientWorker(Socket client) {
this.client = client;
}
public void run(){
String line;
BufferedReader in = null;
PrintWriter out = null;
try{
in = new BufferedReader(new
InputStreamReader(client.getInputStream()));
//out = new
// PrintWriter(client.getOutputStream(), true);
} catch (IOException e) {
System.out.println("in or out failed");
System.exit(-1);
}
while(true){
try{
line = in.readLine();
//Send data back to client
//out.println(line);
//Append data to text area
if(line!=null && line!=""){
System.out.println(line);
try{
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream("out.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
//Read File Line By Line
Socket s;
PrintWriter prnt;
while ((strLine = br.readLine()) != null && (strLine = br.readLine()) != "") {
// Print the content on the console
s = new Socket(strLine, 44441);
prnt = new PrintWriter(s.getOutputStream(),true);
prnt.println(line);
System.out.println(strLine);
prnt.close();
s.close();
}
//Close the input stream
//inp.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}catch (IOException e) {
System.out.println("Read failed");
e.printStackTrace();
System.exit(-1);
}
}
}
}
The Exception starts:
java.net.ConnectException: Connection refused: connect
The expanded output looks like:
I'm somewhat confused as to why you attempt to open a new socket (do you intend for this to be sent back to the client?) based on a string you read from a file. Perhaps
s = new Socket(strLine, 44441);
prnt = new PrintWriter(s.getOutputStream(),true);
should be:
prnt = new PrintWriter(client.getOutputStream(),true);
As currently I don't see where you are sending anything back to the client.
Edit: ok try something like the following:
static final ArrayList<ClientWorker> connectedClients = new ArrayList<ClientWorker>();
class ClientWorker implements Runnable {
private Socket socket;
private PrintWriter writer;
ClientWorker(Socket socket) {
this.socket = socket;
try {
this.writer = new PrintWriter(socket.getOutputStream(), true);
} catch (IOException ex) { /* do something sensible */ }
}
public void run() {
synchronized(connectedClients) {
connectedClients.add(this);
}
BufferedReader in = null;
try {
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
} catch (IOException e) { /* do something sensible */ }
while (true) {
try {
String line = in.readLine();
if (line != null && line != "") {
synchronized (connectedClients) {
for (int i = 0; i < connectedClients.size(); ++i){
ClientWorker client = connectedClients.get(i);
client.writer.println(line);
}
}
}
} catch (IOException e) { /* do something sensible */ }
}
}
}

Categories

Resources