Detecting disconnects in sockets - java

I'm creating an "echo" server that upon receiving a message simply sends it back. I have managed to get multi-client working, but I want to make some kind of disconnect detection. I tried to get it working through sending a single character from the server, then replying with another character from the client. I couldn't get this to work, though.
How would you suggest I go about disconnect detection?
MessageServer.java
import java.net.*;
import java.io.*;
public class MessageServer {
static int clientCount = 0;
public static void main(String[] args) throws IOException {
try(ServerSocket servSocket = new ServerSocket(16384)){
while(true){
Socket socket = servSocket.accept();
addClient();
new ServerThread(socket, clientCount).start();
}
} catch(IOException e) {
System.out.println("Exception caught when trying to listen on port 16384 or listening for a connection");
System.out.println(e.getMessage());
}
}
public static void addClient(){
clientCount++;
}
}
ServerThread.java
import java.net.*;
import java.io.*;
public class ServerThread extends Thread {
private Socket cltSocket;
private BufferedReader in;
private PrintWriter out;
private int num;
public ServerThread(Socket clientSocket, int count) {
cltSocket = clientSocket;
num = count;
}
public void run() {
String input;
try {
out = new PrintWriter(cltSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(cltSocket.getInputStream()));
System.out.println("Client " + num + " connected!");
while(cltSocket.isConnected() && !cltSocket.isClosed()){
if(in.ready()){
input = in.readLine();
if(input != null && !(input.equalsIgnoreCase("exit"))){
System.out.print("New input: ");
System.out.println(input);
out.println(input);
out.flush();
} else if(input.equalsIgnoreCase("exit")){
disconnect();
}
}
}
} catch(SocketException e) {
disconnect();
} catch (IOException e) {
e.printStackTrace();
return;
}
}
public void disconnect(){
System.out.println("Client " + num + " disconnected!");
out.close();
try {
in.close();
cltSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
MessageClient.java
import java.net.*;
import java.io.*;
public class MessageClient {
public static void main(String[] args) {
if(args.length != 2) {
System.out.println("Invalid parameters! Format as: (hostname) (port)");
System.exit(1);
}
String hostname = args[0];
int port = Integer.parseInt(args[1]);
try {
Socket socket = new Socket(hostname, port);
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
BufferedReader con = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Connected!");
while(socket.isConnected() && !socket.isClosed()){
String output;
if(con.ready()) {
output = con.readLine();
out.println(output);
if(output.equalsIgnoreCase("exit")) {
socket.close();
}
}
if(in.ready()){
String li = in.readLine();
if(li != null) {
System.out.println(li);
}
}
}
System.out.println("Disconnected!");
con.close();
out.close();
in.close();
System.exit(0);
} catch(SocketException e) {
System.err.println("Socket error:" + e);
} catch(UnknownHostException e) {
System.err.println("Invalid host");
} catch(IOException e) {
System.err.println("IO Error: " + e);
}
}
}

There is a way to do that:
if you read the BufferedReader by calling BufferedReader.getLine() and the other side socket is gone, then you get an SocketException... that is a way to check a lost connection

Related

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);
}

Java Client Server - Multiple Event Handling for the Client

I'm trying to setup a client server application using socket programming. My client connects to the server, but I'm unable to get the multiple event handling to work. My client applet has two text boxes and buttons associated with each one of of them. When I click button one, I was trying to get "Hello" to be displayed in the text box. When I click on button two, I was trying to get "Hello there" to be displayed in the second text box. However, only one value (the value I first click) shows up in both of the text boxes. Is my event handling mechanism incorrect? I am implementing the serializable interface and the client server communication deals with objects. Can someone please tell me what the problem in the code is? I haven't posted the ObjectCommunication.java code, but it simply implements the serializable interface and has the getter and setter (takes a string as an input parameter) method.
Many thanks!
The following is my server code:
import java.io.*;
import java.net.*;
public class Server_App {
public static void main(String[] args) {
try {
ServerSocket holder = new ServerSocket(4500);
for (;;) {
Socket incoming = holder.accept();
new ServerThread(incoming).start();
}
} catch (Exception e) {
System.out.println(e);
}
}
}
class ServerThread extends Thread
{
public ServerThread(Socket i) {
incoming = i;
}
public void run() {
try {
ObjectCommunication hold = new ObjectCommunication();
ObjectInputStream input = new ObjectInputStream(incoming.getInputStream());
ObjectOutputStream output = new ObjectOutputStream(incoming.getOutputStream());
hold = (ObjectCommunication) input.readObject();
if ((hold.getMessage()).equals("Event 1")) {
System.out.println("Message read: " + hold.getMessage());
hold.setMessage("Hello!");
} else if ((hold.getMessage()).equals("Event 2")) {
System.out.println("Message read:" + hold.getMessage());
hold.setMessage("Hello there!");
}
output.writeObject(hold);
input.close();
output.close();
incoming.close();
} catch (Exception e) {
System.out.println(e);
}
}
ObjectCommunication hold = null;
private Socket incoming;
}
The following is the client code:
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
public class Client_App extends Applet {
TextField textVal;
TextField anotherTextVal;
Socket socket;
ObjectCommunication hold = new ObjectCommunication();
ObjectCommunication temp = new ObjectCommunication();
ObjectOutputStream OutputStream;
ObjectInputStream InputStream;
public void init() {
socketConnection();
createGUI();
validate();
}
public void socketConnection() {
try {
socket = new Socket("127.0.0.1", 4500);
} catch (Exception e) {
System.out.println("Unknown Host");
}
try {
OutputStream = new ObjectOutputStream(socket.getOutputStream());
InputStream = new ObjectInputStream(socket.getInputStream());
} catch (IOException ex) {
System.out.println("Error: " + ex);
return;
}
}
public void createGUI() {
Button button = new Button("Hello Button");
add(button);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
button_actionPerformed(evt);
}
});
textVal = new TextField(6);
add(textVal);
Button anotherButton = new Button("Hello there Button");
add(anotherButton);
anotherButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
anotherButton_actionPerformed(evt);
}
});
anotherTextVal = new TextField(6);
add(anotherTextVal);
}
public void button_actionPerformed(ActionEvent e) {
String actionCommand = e.getActionCommand();
if (e.getSource() instanceof Button)
if (actionCommand.equals("Hello Button")) {
try {
temp.setMessage("Event 1");
//OutputStream.writeObject(temp);
new SendToServer().start();
new ListenToServer().start();
} catch (Exception ex) {
System.out.println("Communication didn't work!");
}
textVal.setText(hold.getMessage());
}
}
public void anotherButton_actionPerformed(ActionEvent evt) {
String action_Command = evt.getActionCommand();
if (evt.getSource() instanceof Button)
if (action_Command.equals("Hello there Button")) {
try {
temp.setMessage("Event 2");
new SendToServer().start();
new ListenToServer().start();
} catch (Exception ex) {
System.out.println("Communication didn't work!");
}
anotherTextVal.setText(hold.getMessage());
}
}
class ListenToServer extends Thread {
public void run() {
while (true) {
try {
hold = (ObjectCommunication) InputStream.readObject();
} catch (IOException e) {} catch (ClassNotFoundException e2) {}
}
}
}
class SendToServer extends Thread {
public void run() {
while (true) {
try {
OutputStream.writeObject(temp);
} catch (IOException e) {}
}
}
}
}
To be honest - I'm a little bit lazy to read through your code and seek there for a bug :) Nevertheless I'll post you here my snippet for socket-based multiple client-server application..
import java.net.*;
import java.io.*;
class ServeConnection extends Thread {
private Socket socket = null;
private BufferedReader in = null;
private PrintWriter out = null;
public ServeConnection(Socket s) throws IOException {
// init connection with client
socket = s;
try {
in = new BufferedReader(new InputStreamReader(
this.socket.getInputStream()));
out = new PrintWriter(this.socket.getOutputStream(), true);
} catch (IOException e) {
System.err.println("Couldn't get I/O.");
System.exit(1);
}
start();
}
public void run() {
System.out.println("client accepted from: " + socket.getInetAddress()
+ ":" + socket.getPort());
// get commands from client, until is he communicating or until no error
// occurs
String inputLine, outputLine;
try {
while ((inputLine = in.readLine()) != null) {
System.out.println("request: " + inputLine);
outputLine = inputLine;
out.println("I've recived "+outputLine);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("server ending");
out.close();
try {
in.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
class Server {
public static void svr_main(int port) throws IOException {
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(port);
} catch (IOException e) {
System.err.println("Could not listen on port: " + port);
System.exit(1);
}
System.out.println("Server ready");
try {
while (true) {
Socket socket = serverSocket.accept();
try {
new ServeConnection(socket);
} catch (IOException e) {
System.err.println("IO Exception");
}
}
} finally {
serverSocket.close();
}
}
}
class Client {
static Socket echoSocket = null;
static PrintWriter out = null;
static BufferedReader in = null;
public static void cli_main(int port, String servername) throws
IOException {
try {
echoSocket = new Socket(servername, port);
out = new PrintWriter(echoSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(
echoSocket.getInputStream()));
} catch (UnknownHostException e) {
System.err.println("Don't know about host: " + servername);
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for " + servername);
System.exit(1);
}
System.out.println("Client ready!");
while (true) {
inputLine = (in.readLine().toString());
if (inputLine == null) {
System.out.println("Client closing!");
break;
}
// get the input and tokenize it
String[] tokens = inputLine.split(" ");
}
out.close();
in.close();
echoSocket.close();
System.out.println("Client closing");
}
}
public class MyClientServerSnippet{
public static void main(String[] args) throws IOException {
if (args.length == 0) {
System.err.println("Client: java snippet.MyClientServerSnippet<hostname> <port>");
System.err.println("Server: java snippet.MyClientServerSnippet<port>");
System.exit(1);
}
else if (args.length > 1) {
System.out.println("Starting client...\n");
Client client = new Client();
client.cli_main(3049, "127.0.0.1");
} else {
System.out.println("Starting server...\n");
Server server = new Server();
server.svr_main(3049);
}
}
}
Hope this helps :] If anything would be ununderstandable, don't hesitate to ask for more details :)

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 */ }
}
}
}

Multithreaded chat-server in Java

I'm trying to implement a server-client socket program in Java that can support multiple clients, but my class that performs the multithreading always crashes whenever my client connects to my server.
import java.io.*;
import java.net.*;
public class ClientWorker extends Thread{
Socket cwsocket=null;
public ClientWorker(Socket cwsocket){
super("ClientWorker");
cwsocket=cwsocket;
}
public void run(){
try {
PrintWriter out = new PrintWriter(cwsocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(cwsocket.getInputStream()));
String serverinput, serveroutput="";
out.println(serveroutput);
while ((serverinput = in.readLine()) != null) {
out.println(serveroutput);
if (serveroutput.equals("Terminate"))
break;
}
out.close();
in.close();
cwsocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Whenever I create a PrintWriter object, a NullPointerException exception is thrown, and I'm not sure why it continues to happen. Below are my server and client classes. What am I doing wrong?
import java.io.*;
import java.net.*;
public class Server {
public static void main(String[]args)throws IOException{
ServerSocket serversocket=null;
final int PORT_NUM=4444;
boolean flag=true;
try{
System.out.println("Listening for connection");
serversocket=new ServerSocket(PORT_NUM);
}catch(IOException e){
System.out.println("Could not listen to port: "+PORT_NUM);
System.exit(-1);
}
while(flag){
new ClientWorker(serversocket.accept()).start();
}
System.out.println("Terminating server...");
serversocket.close();
}
}
import java.io.*;
import java.net.*;
public class Client {
public static void main(String[] args){
Socket socket=null;
PrintWriter out=null;
BufferedReader in=null;
BufferedReader userInputStream=null;
String IP="127.0.0.1";
try{
socket = new Socket(IP, 4444);
out = new PrintWriter(socket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
} catch (UnknownHostException e) {
System.out.println("Unknown host:" + IP);
System.exit(1);
} catch (IOException e) {
System.out.println("Cannot connect to server...");
System.exit(1);
}
String userInput, fromServer;
try{
userInputStream = new BufferedReader(new InputStreamReader(System.in));
while ((fromServer = in.readLine()) != null) {
System.out.println("Server: " + fromServer);
if (fromServer.equals("Terminate"))
break;
userInput = userInputStream.readLine();
if (userInput != null) {
System.out.println("> " + userInput);
out.println(userInput);
}
}
}catch(IOException e){
System.out.println("Bad I/O");
System.exit(1);
}
try{
out.close();
in.close();
userInputStream.close();
socket.close();
System.out.println("Terminating client...");
}catch(IOException e){
System.out.println("Bad I/O");
System.exit(1);
}catch(Exception e){
System.out.println("Bad I/O");
System.exit(1);
}
}
}
In
public ClientWorker(Socket cwsocket){
super("ClientWorker");
cwsocket=cwsocket;
}
You need to do
this.cwsocket=cwsocket;
Or rename the parameter so it doesn't shadow the member of the same name.

Categories

Resources