How to react to events while blocked by input java - 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) {
}
}
}

Related

SOCKETS keeping client listening

I think the problem is that client 2 is not entering receiving mode and the connection between clients closes before first client sends something to the second... but I might be wrong.
Here is the code of server and clients. Program is based on token ring algorithm. I'm not fluent in Java so I suppose I didn't use the best way to solve it.
Server:
public class TokenServer
{
ServerSocket clientConn;
public TokenServer(int port){
System.out.println("Server connecting to port "+port);
try {
clientConn = new ServerSocket(port);
}
catch (Exception e) {
System.out.println("Exception:"+e);
System.exit(1);
}
}
public static void main(String[] args) {
int port = 8000;
if (args.length > 0) {
try {
port = Integer.parseInt(args[0]);
}
catch (Exception e) {
port = 8000;
}
}
TokenServer server = new TokenServer(port);
System.out.println("Server running on port "+port);
server.listen();
}
public void listen(){
try{
System.out.println("Waiting for clients...");
while(true) {
Socket clientReq = clientConn.accept();
System.out.println("Connection from "+clientReq.getInetAddress().getHostName());
serviceClient(clientReq);
}
}
catch (IOException e) {
System.out.println("Exception:"+e);
}
}
public void serviceClient(Socket s){
System.out.println("New request from "+s.getInetAddress());
ObjectInputStream inStream = null;
ObjectOutputStream outStream = null;
int message_id;
Object message = null;
try{
outStream = new ObjectOutputStream(s.getOutputStream());
inStream = new ObjectInputStream(s.getInputStream());
message_id = inStream.readInt();
System.out.println("Got message "+message_id);
int zmienna;
zmienna = message_id + message_id;
outStream.writeObject(zmienna);
outStream.flush();
}
catch (Exception e) {
System.out.println("Exception:"+e);
}
System.out.println("Done.");
}
}
Client 1:
public class TokenClient1{
int sendport,recport;
boolean hasToken = true;
boolean setSendData = false;
String host;
public TokenClient1(String host){
this.host = host;
}
void setSendPort(int sendport)
{
this.sendport = sendport;
}
void setRecPort(int recport)
{
this.recport = recport;
}
public Object sendMessage(int message_id) throws Exception
{
Socket serverConn;
ObjectInputStream inStream = null;
ObjectOutputStream outStream = null;
Object response = null;
serverConn = new Socket(host, sendport);
outStream = new ObjectOutputStream(serverConn.getOutputStream());
inStream = new ObjectInputStream(serverConn.getInputStream());
outStream.writeInt(message_id);
outStream.flush();
response = inStream.readObject();
serverConn.close();
//hasToken = false;
return response;
}
public Object recData() throws Exception
{
Socket serverConn;
ObjectInputStream inStream = null;
Object response = null;
serverConn = new Socket(host, recport);
inStream = new ObjectInputStream(serverConn.getInputStream());
response = inStream.readObject();
serverConn.close();
if(response.toString().equals("Token"))
{
hasToken = true;
}
return response;
}
public static void main (String[] args){
TokenClient1 client = new TokenClient1("localhost");
TokenClient1 server = new TokenClient1("localhost");
client.setSendPort(8002);
client.setRecPort(8002);
server.setSendPort(8000);
Scanner scan = new Scanner(System.in);
int wybor, zmienna;
try{
while(true)
{
if(client.hasToken == true){
System.out.println("Do you want to enter the Data --> \n1. YES \n0. NO");
wybor = scan.nextInt();
switch (wybor) {
case 1:
{
System.out.println("ready to send \n Podaj liczbe do dodania: ");
//server.setSendData = true;
zmienna = scan.nextInt();
System.out.println("odpowiedz servera:");
System.out.println((Integer)server.sendMessage(zmienna));
break;
}
case 0:
{
System.out.println("i m in else");
client.sendMessage(0);
client.recData();
System.out.println("i m leaving else");
break;
}
}
}
else {
System.out.println("ENTERING RECEIVING MODE...");
client.recData();
}
}
}
catch(Exception e) {
System.out.println("Esception:"+e);
}
}
}
Client 2:
public class TokenClient2
{
int sendport,recport;
boolean hasToken = false;
String host;
ServerSocket clientConn;
public TokenClient2(String host){
this.host = host;
}
void setSendPort(int sendport)
{
this.sendport = sendport;
}
void setRecPort(int recport)
{
this.recport = recport;
}
public Object sendMessage(int message_id) throws Exception
{
Socket serverConn;
ObjectInputStream inStream = null;
ObjectOutputStream outStream = null;
Object response = null;
serverConn = new Socket(host, sendport);
outStream = new ObjectOutputStream(serverConn.getOutputStream());
inStream = new ObjectInputStream(serverConn.getInputStream());
outStream.writeInt(message_id);
outStream.flush();
response = inStream.readObject();
serverConn.close();
//hasToken = false;
return response;
}
void recData() throws Exception
{
try{
System.out.println("Waiting for clients...");
// while(true) {
Socket serverConn;
ObjectInputStream inStream = null;
Object response = null;
clientConn = new ServerSocket(8002);
serverConn = new Socket(host, 8000);
Socket clientReq = clientConn.accept();
System.out.println("Connection from "+clientReq.getInetAddress().getHostName());
inStream = new ObjectInputStream(serverConn.getInputStream());
response = inStream.readObject();
clientConn.close();
System.out.println("Waiting for cents...");
if(response.equals(0))
{
System.out.println("tdfss...");
hasToken = true;
}
//return response;
}
//}
catch (IOException e) {
System.out.println("Exception:"+e);
}
}
public static void main (String[] args){
TokenClient2 client = new TokenClient2("localhost");
TokenClient2 server = new TokenClient2("localhost");
client.setSendPort(8002);
client.setRecPort(8002);
server.setSendPort(8000);
Scanner scan = new Scanner(System.in);
int wybor, zmienna;
try{
while(true)
{
if(client.hasToken == true){
System.out.println("Do you want to enter the Data --> \n1. YES \n0. NO");
wybor = scan.nextInt();
switch (wybor) {
case 1:
{
System.out.println("ready to send \n Podaj liczbe do dodania: ");
//server.setSendData = true;
zmienna = scan.nextInt();
System.out.println("odpowiedz servera:");
System.out.println((Integer)server.sendMessage(zmienna));
break;
}
case 0:
{
System.out.println("i m in else");
client.sendMessage(0);
client.recData();
System.out.println("i m leaving else");
break;
}
}
}
else {
client.hasToken=true;
System.out.println("ENTERING RECEIVING MODE...");
client.recData();
}
}
}
catch(Exception e) {
System.out.println("Esception:"+e);
}
}
}

Chat server client sometimes cannot see message from other clients on the same server

I am making 2 classes for Chat server client for a project I am working on. The problem is server can see the message that sent to it(from client) and it can send those messages out to every clients BUT each client has to type in some input first if he wants to see the message from other users. I have no clue what I did wrong. Please help me out. Thanks in advance :)
Server Class
import java.net.*;
import java.util.ArrayList;
import java.io.*;
public class TestServer extends Thread
{
protected Socket clientSocket;
public static ArrayList<Socket> ConnectionArray = new ArrayList<Socket>();
public static ArrayList<String> CurrentUsers = new ArrayList<String>();
final static int PORT = 22;
public static void main(String[] args) throws IOException
{
ServerSocket serverSocket = null;
try
{
serverSocket = new ServerSocket(PORT);
System.out.println ("Connection Socket Created");
try
{
while (true)
{
System.out.println ("Waiting for Connection");
Socket sock = serverSocket.accept();
ConnectionArray.add(sock);
System.out.println("Client connected from: " + sock.getLocalAddress().getHostName());
new TestServer (sock);
}
}
catch (IOException e)
{
System.err.println("Accept failed.");
System.exit(1);
}
}
catch (IOException e)
{
System.err.println("Could not listen on port: " + PORT);
System.exit(1);
}
finally
{
try {
serverSocket.close();
}
catch (IOException e)
{
System.err.println("Could not close port: 10008.");
System.exit(1);
}
}
}
private TestServer (Socket inSock)
{
clientSocket = inSock;
start();
}
public void run()
{
System.out.println ("New Communication Thread Started");
//System.out.println ("Client connected from: " + sock.getLocalAddress().getHostName());
try {
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(),true);
BufferedReader in = new BufferedReader(new InputStreamReader( clientSocket.getInputStream()));
String inputLine;
while (true)
{
inputLine = in.readLine();
System.out.println ("Server: " + inputLine);
for(int i = 1; i <= TestServer.ConnectionArray.size(); i++)
{
System.out.println("Total Connection: " + ConnectionArray.size());
Socket TEMP_SOCK = (Socket) TestServer.ConnectionArray.get(i-1);
if (clientSocket != TEMP_SOCK)
{
PrintWriter TEMP_OUT = new PrintWriter(TEMP_SOCK.getOutputStream(), true);
TEMP_OUT.println(inputLine);
TEMP_OUT.flush();
System.out.println("Sending to: " + TEMP_SOCK.getLocalAddress().getHostName());
}
}
if (inputLine.equals("Bye."))
break;
}
out.close();
in.close();
clientSocket.close();
}
catch (IOException e)
{
System.err.println("Problem with Communication Server");
System.exit(1);
}
}
}
Client Class
import java.io.*;
import java.net.*;
public class TestClient {
public static void main(String[] args) throws IOException {
String serverHostname = new String ("127.0.0.1");
if (args.length > 0)
serverHostname = args[0];
System.out.println ("Attemping to connect to host " +
serverHostname);
Socket echoSocket = null;
PrintWriter out = null;
BufferedReader in = null;
try {
echoSocket = new Socket(serverHostname, 22);
out = new PrintWriter(echoSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(echoSocket.getInputStream()));
} catch (UnknownHostException e) {
System.err.println("Don't know about host: " + serverHostname);
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for "
+ "the connection to: " + serverHostname);
System.exit(1);
}
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
String userInput;
System.out.println ("Type Message (\"Bye.\" to quit)");
while ((userInput = stdIn.readLine()) != null)
{
out.println(userInput);
if (userInput.equals("Bye."))
break;
System.out.println("Other user: " + in.readLine());
}
out.close();
in.close();
stdIn.close();
echoSocket.close();
}
}
You need a separate thread in the client for reading from the server without blocking on System.in;
Thread t = new Thread(() -> {
try {
while (!Thread.currentThread().isInterrupted()) {
System.out.println("Other user: " + in.readLine());
}
} catch (Exception e) {
e.printStackTrace();
}
});
t.start();
while ((userInput = stdIn.readLine()) != null)
{
out.println(userInput);
if (userInput.equals("Bye."))
break;
}
t.interrupt();

Why isn't my socket revieving the message?

I'm trying to learn how to use java sockets before next semester. I wrote this program that is supposed to accept accept a message from a sender and send the message to a reciever. You specify the reciever by writing the name of the client that is connected, if the client isn't connected then the server will respond by sending the message "DISCONNECTED". But for some reason the message isn't sent to the reciever. I can still send the message to the sender though. Is this the right forum to ask for this kind of help?
This is my client class
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
public class MyTestClient {
static int port = 0;
static String ip = "";
static String name = "";
public static void main(String args[] ) {
if(args.length == 3) {
try{
port = Integer.parseInt(args[1]);
} catch(NumberFormatException e) {
System.out.println("Usage: Java MyTestClient <ip> <port> <name>");
System.exit(0);
}
ip = args[0];
name = args[2];
} else {
System.out.println("Usage: Java MyTestClient <ip> <port> <name>");
System.exit(0);
}
try {
Socket socket = new Socket(ip, port);
new Thread(new MessageHandler(socket)).start();
new Thread(new InputHandler(socket)).start();
} catch (IOException e) {
System.out.println("Could not connect to: " + ip + " : " + port);
System.exit(0);
}
}
public static class MessageHandler implements Runnable {
Socket socket;
public MessageHandler(Socket socket) {
this.socket = socket;
}
#Override
public void run() {
PrintWriter out = null;
BufferedReader in = null;
try {
out = new PrintWriter(socket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
}catch(IOException e) {
e.printStackTrace();
}
String fromServer;
try {
while ((fromServer = in.readLine()) != null) {
System.out.println(fromServer);
fromServer.trim();
if(fromServer.contains(" ")) {
String split[] = fromServer.split(" ", 2);
System.out.println(split.length == 2 ? split[1] + " Is a two part message" : "Strange message");
} else {
if(fromServer.equals("NAME")) {
System.out.println("Server asks for name | gives given name to server");
out.println(name);
}
if(fromServer.equals("SUCCESS")) {
System.out.println("Message succesfully sent");
}
if(fromServer.equals("ERROR")) {
System.out.println("Something went wrong when sending the message");
}
if(fromServer.equals("OCCUPIED")) {
System.out.println("Name was already used. Start the program with another name");
socket.close();
System.exit(0);
}
if(fromServer.equals("DISCONNECTED")) {
System.out.println("The reciever was not connected");
}
if(fromServer.equals("REGISTERED")) {
System.out.println("Successfully logged in to server");
}
}
}
} catch(IOException e) {
e.printStackTrace();
}
}
}
public static class InputHandler implements Runnable {
Socket socket;
public InputHandler(Socket socket) {
this.socket = socket;
}
#Override
public void run() {
String fromUser = null;
PrintWriter out = null;
try {
out = new PrintWriter(socket.getOutputStream(), true);
} catch (IOException e) {
e.printStackTrace();
}
BufferedReader kbi = new BufferedReader(new InputStreamReader(System.in));
try {
while ((fromUser = kbi.readLine()) != null) {
out.println(fromUser);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
This is my server class
import java.io.*;
import java.net.*;
import java.util.*;
public class MyServer {
public static int port;
public static int maxConnections;
public static final String NAME = "Server";
private static Map<String, Socket> socketsMap = new HashMap<>();
public static void main(String args[]) {
if(args.length == 2) {
try{
port = Integer.parseInt(args[0]);
maxConnections = Integer.parseInt(args[1]);
}catch(Exception e){
System.out.println("Usage: Java Myserver <port> <maxConnections>");
System.exit(0);
}
} else {
System.out.println("Usage: Java Myserver <port> <maxConnections>");
System.exit(0);
}
new Thread(new ConnectionHandler(port, maxConnections)).start();
}
public static class ConnectionHandler implements Runnable {
private ServerSocket server;
private Socket socket = null;
public int currentSocket = 0;
public int port = 0;
public int maxConnections = 0;
public ConnectionHandler(int port, int maxConnections) {
this.maxConnections = maxConnections;
this.port = port;
}
#Override
public void run() {
try {
server = new ServerSocket(7777);
} catch (IOException e1) {
System.out.println("Server could not connect to port: " + port);
e1.printStackTrace();
System.exit(0);
}
while(currentSocket++ < maxConnections) {
try {
socket = server.accept();
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out.println("NAME");
String message;
while((message = in.readLine()) != null) {
if(!socketsMap.containsKey(message) || message.equals("SERVER")) {
out.println("REGISTERED");
socketsMap.put(message, socket);
System.out.println(message + " has logged on server");
new Thread(new SocketHandler(socketsMap.get(message))).start();
} else {
out.println("OCCUPIED");
System.out.println(socket.getInetAddress().toString() + " has tried to login with existing name " + message);
socket.close();
currentSocket--;
}
socket = null;
break;
}
} catch (IOException e) {
System.out.println("Something went wrong with client connection");
}
}
}
}
public static class SocketHandler implements Runnable {
Socket socket = null;
public SocketHandler(Socket socket) {
this.socket = socket;
}
#Override
public void run() {
try {
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter respond = new PrintWriter(socket.getOutputStream(), true);
String input;
while((input = in.readLine() ) != null) {
String[] info = input.split(" ", 2);
if(info.length != 2){
System.out.println("Message computed wrong");
respond.println("ERROR");
break;
}
if(info[0].equals("SERVER")) {
//TODO: Write a server command handler class
} else if ( socketsMap.containsKey(info[0]) ){
Socket reciever = socketsMap.get(info[0]);
PrintWriter out = new PrintWriter(reciever.getOutputStream());
respond.println("SUCCESS");
System.out.println(info[0] + " send the message: "+ info[1]);
out.println("MESSAGE" + " " + info[1]);
break;
} else {
System.out.println("Reciever is not connected");
respond.println("DISCONNECTED");
}
}
}catch(IOException e) {
e.printStackTrace();
}
}
}
}
Maybe you can run it on your computers and see what i mean?
#Override
public void run() {
try {
server = new ServerSocket(7777);
} catch (IOException e1) {
System.out.println("Server could not connect to port: " + port);
e1.printStackTrace();
System.exit(0);
}
change the code above to
#Override
public void run() {
try {
server = new ServerSocket(port);
} catch (IOException e1) {
System.out.println("Server could not connect to port: " + port);
e1.printStackTrace();
System.exit(0);
}

Socket gets Closed after 1st command

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.

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