I am writing a simple socket programming application that uses a server and one client. I am trying to start a thread (from client file) that reads input from the socket input stream so that i can write messages to the server and read them back and print them to the screen at the same time. However, when i run my code, my code gets stuck at
message = in.readLine();
in InputReader.java file and reads no input?
My code is as follows, please help.
SimpleServer1.java
public class SimpleServer1 {
public static void main(String args[]){
int portNumber = Integer.parseInt(args[0]);
ServerSocket serverSocket = null;
Socket clientConnection = null;
try{
//setup sockets
serverSocket = new ServerSocket(portNumber);
clientConnection = serverSocket.accept();
System.out.println("Connected to" + clientConnection.getInetAddress());
//setup streams
BufferedReader in = new BufferedReader(new InputStreamReader(clientConnection.getInputStream()));
PrintWriter out = new PrintWriter(clientConnection.getOutputStream());
out.flush();
//read input from stream
String message;
while((message = in.readLine()) != null){
//return message to client
out.println("Echo: " + message);
System.out.println(clientConnection.getInetAddress() + ": " + message);
if (message.equalsIgnoreCase("bye")){
System.out.println("Closing connection...");
break;
}
}
//close streams
out.close();
in.close();
clientConnection.close();
}catch(Exception e){
e.printStackTrace();
}
}
SimpleClient1.java
public class SimpleClient1{
public static void main(String args[]){
String hostName = (args[0]);
int portNumber = Integer.parseInt(args[1]);
try{
Socket serverConnection = new Socket(hostName, portNumber);
PrintWriter out = new PrintWriter(serverConnection.getOutputStream(), true);
out.flush();
Thread listener = new Thread(new InputReader(serverConnection));
listener.start();
Scanner keyboard = new Scanner(System.in);
String userInput;
while((userInput = keyboard.nextLine()) != null){
out.println(userInput);
if (userInput.equalsIgnoreCase("bye")){
break;
}
}
//closing streams
out.close();
serverConnection.close();
}catch(Exception e){
e.printStackTrace();
}
}
InputReader.java <-- what i am trying to run my thread with
public class InputReader implements Runnable{
private Socket serverConnection;
private BufferedReader in;
public InputReader(Socket socket){
serverConnection = socket;
try{
in = new BufferedReader(new InputStreamReader(serverConnection.getInputStream()));
}catch(IOException ioE){ioE.printStackTrace();}
}
#Override
public void run() {
try{
String message;
while(true){
System.out.println("done");
message = in.readLine();
System.out.println(message);
}
}catch(IOException ioE){ioE.printStackTrace();}
}
Ultimately, I would like to both read and write from the socket streams using threads.
Thanks in advance :)
Cobezz
I believe you have to flush the stream you are writing to after you have written to it. You appear to flush the stream as soon as you create it, which won't have any effect.
in SimpleServer1.java you must be add out.flush();
while ((message = in.readLine()) != null) {
out.println("Echo: " + message);
out.flush();
System.out.println(clientConnection.getInetAddress() + ": " + message);
if (message.equalsIgnoreCase("bye")){
System.out.println("Closing connection...");
break;
}
}
Related
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I'm trying to create a program where a client and server send text messages to each other (in utf-8 string format) similar to how two phones text message each other. Eventually I will need to create four lines (two to encode/decode utf-8 string on server side) (two to encode/decode utf-8 string on client side) This program uses two threads, one for the client one for the server.
Screenshot of error in mac terminal (command prompt)
There were no errors before I changed the following lines of code:
String MessageFromClientEncodedUTF8 = "";
BufferedReader BufReader1 = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8"));
socket = serverSocket.accept();
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String MessageFromClientDecodedFromUTF8 = BufReader1.readLine();
System.out.println("The message is currently encoded UTF-8");
byte[] bytes = MessageFromClientEncodedUTF8.getBytes("UTF-8");
String MessageFromClientDecodedUTF8 = new String(bytes, "UTF-8");
System.out.println("Message received from client (decoded utf-8): "+ MessageFromClientDecodedUTF8);
There are three files: the main function file, the server file, and the client file. When the main function file runs, if the "-l" command line argument is present, the server file will run, otherwise the client will run.
Server file (DirectMessengerServer.java):
import java.io.*;
import java.net.*;
import java.util.*;
import static java.nio.charset.StandardCharsets.*;
public class DirectMessengerServer
{
private static Socket socket;
boolean KeepRunning = true;
void ServerRun(String[] args)
{
Thread Server = new Thread ()
{
public void run ()
{
System.out.println("Server thread is now running");
try
{
System.out.println("Try block begins..");
int port_number1= Integer.valueOf(args[1]);
System.out.println("Port number is: " + port_number1);
ServerSocket serverSocket = new ServerSocket(port_number1);
//SocketAddress addr = new InetSocketAddress(address, port_number1);
System.out.println( "Listening for connections on port: " + ( port_number1 ) );
while(KeepRunning)
{
//Reading the message from the client
String MessageFromClientEncodedUTF8 = "";
BufferedReader BufReader1 = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8"));
socket = serverSocket.accept();
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String MessageFromClientDecodedFromUTF8 = BufReader1.readLine();
System.out.println("The message is currently encoded UTF-8");
byte[] bytes = MessageFromClientEncodedUTF8.getBytes("UTF-8");
String MessageFromClientDecodedUTF8 = new String(bytes, "UTF-8");
System.out.println("Message received from client (decoded utf-8): "+ MessageFromClientDecodedUTF8);
//Shut down with zero-length message
if(MessageFromClientDecodedFromUTF8.equals(""))
{
KeepRunning=false;
System.out.println("Shutting down");
System.exit(0);
socket.close();
serverSocket.close();
}
if(MessageFromClientDecodedFromUTF8.equals(null))
{
KeepRunning=false;
System.out.println("Shutting down");
System.exit(0);
socket.close();
serverSocket.close();
}
if(MessageFromClientDecodedFromUTF8=="")
{
KeepRunning=false;
System.out.println("Shutting down");
System.exit(0);
socket.close();
serverSocket.close();
}
if(MessageFromClientDecodedFromUTF8==null)
{
KeepRunning=false;
System.out.println("Shutting down");
System.exit(0);
socket.close();
serverSocket.close();
}
if(MessageFromClientDecodedFromUTF8=="\n")
{
KeepRunning=false;
System.out.println("Shutting down");
System.exit(0);
socket.close();
serverSocket.close();
}
//creating message to server send from standard input
String newmessage = "";
try {
// input the message from standard input
BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8"));
String line = "";
System.out.println( "Standard input (press enter then control D when finished): " );
while( (line= input.readLine()) != null && KeepRunning==true )
{
newmessage += line + " \n ";
}
}
catch ( Exception e ) {
System.out.println( e.getMessage() );
}
//Writing return message back to client
String returnMessage = newmessage;
OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
bw.write(returnMessage + "\n");
System.out.println("Message sent to client: "+returnMessage);
bw.flush();
}
}
catch ( Exception e )
{
e.printStackTrace();
}
finally
{
//Closing the socket
try
{
socket.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
};
Server.start();
}
}
Client file (DirectMessengerClient.java):
import java.io.*;
import java.net.*;
import java.util.*;
import static java.nio.charset.StandardCharsets.*;
public class DirectMessengerClient
{
boolean KeepRunning = true;
private static Socket socket;
//static String[] arguments;
//public static void main(String[] args)
//{
// arguments = args;
//}
public DirectMessengerClient()
{
//System.out.println("test.");
}
public void ClientRun(String[] args)
{
Thread Client = new Thread ()
{
public void run()
{
System.out.println("Client thread is now running");
try
{
System.out.println("Try block begins..");
String port_number1= args[0];
System.out.println("Port number is: " + port_number1);
int port = Integer.valueOf(port_number1);
System.out.println("Listening for connections..");
System.out.println( "Listening on port: " + port_number1 );
while(KeepRunning)
{
String host = "localhost";
InetAddress address = InetAddress.getByName(host);
socket = new Socket(address, port);
//Send the message to the server
OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
//creating message to send from standard input
String newmessage = "";
try
{
// input the message from standard input
BufferedReader input= new BufferedReader(
new InputStreamReader(System.in));
String line = "";
System.out.println( "Standard input (press enter then control D when finished): " );
while( (line= input.readLine()) != null )
{
newmessage += line + " ";
}
}
catch ( Exception e )
{
System.out.println( e.getMessage() );
}
String sendMessage = newmessage;
bw.write(sendMessage + "\n"); // <--- ADD THIS LINE
bw.flush();
System.out.println("Message sent to server: "+sendMessage);
//Get the return message from the server
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String MessageFromServer = br.readLine();
System.out.println("Message received from server: " + MessageFromServer);
if(MessageFromServer.equals(""))
{
KeepRunning=false;
System.out.println("Shutting down");
System.exit(0);
socket.close();
}
if(MessageFromServer.equals(null))
{
KeepRunning=false;
System.out.println("Shutting down");
System.exit(0);
socket.close();
}
if(MessageFromServer=="")
{
KeepRunning=false;
System.out.println("Shutting down");
System.exit(0);
socket.close();
}
if(MessageFromServer==null)
{
KeepRunning=false;
System.out.println("Shutting down");
System.exit(0);
socket.close();
}
if(MessageFromServer=="\n")
{
KeepRunning=false;
System.out.println("Shutting down");
System.exit(0);
socket.close();
}
}
}
catch ( Exception e )
{
e.printStackTrace();
}
finally
{
//Closing the socket
try
{
socket.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
};
Client.start();
}
}
Main function file (DirectMessengerCombined.java):
public class DirectMessengerCombined
{
public static void main(String[] args)
{
DirectMessengerClient Client1 = new DirectMessengerClient();
DirectMessengerServer Server1 = new DirectMessengerServer();
for (int i = 0; i < args.length; i++)
{
if(!args[0].equals("-l"))
{
Client1.ClientRun(args);
}
switch (args[0].charAt(0))
{
case '-':
if(args[0].equals("-l"))
{
Server1.ServerRun(args);
}
}
i=args.length + 20;
}
}
}
My question is: How do I change the way the strings are encoded or decoded in order to send strings to the other side or how to solve the null pointer exception error?
It is because you are trying to get the inputstream of a socket before it exists:-
BufferedReader BufReader1 = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8"));
socket = serverSocket.accept();
These two lines should be the other way around. :)
EDIT: Looking further at your code, you are creating BufReader1 (which is causing the error) and then creating br in exactly the same way, i.e. both are a BufferedReader of the socket. You only need one; having two will probably cause problems for the readers.
so i've been making a simple chat, than has a server and a bunch of clients connected to them. On the client side i have class ConnectionManager to manage creating socket and such. Here is it's core method:
public class ConnectionManager {
private Socket socket;
private BufferedReader reader;
private PrintWriter writer;
public ConnectionManager(String URL, int port){
tryConnectToServer(URL, port);
}
public BufferedReader getReader() {
return reader;
}
public PrintWriter getWriter() {
return writer;
}
private void tryConnectToServer(String ip, int servSocket) {
try{
socket = new Socket(ip, servSocket);
writer = new PrintWriter(socket.getOutputStream());
reader = new BufferedReader(
new InputStreamReader(
socket.getInputStream()));
}
catch (IOException ex){
System.out.println("Unable to connect to specified server. Code pink");
ex.printStackTrace();
}
}
Connection Manager object is a part of ChatGUI. ChatGUI's fields writer and reader are obtained and set from CM in order to pass writer along with ChatGUI's JTextField (msgInput) to SendButtonListener:
private void addSendButton() {
JButton sendButton = new JButton("Send");
sendButton.addActionListener(new SendButtonActionListener(writer, msgInput));
panel.add(sendButton);
panel.add(this.msgArea);
}
Then, actionPerformed method does:
public class SendButtonActionListener implements ActionListener{
private PrintWriter writer;
private JTextField msgInput;
public SendButtonActionListener(PrintWriter pr, JTextField mi){
writer = pr;
msgInput = mi;
}
public void actionPerformed(ActionEvent event){
writer.println(msgInput.getText());
System.out.println("Sending: " + msgInput.getText());
flushMessageInputField();
}
private void flushMessageInputField(){
msgInput.setText("");
}
}
On the server side on the other hand i've got this:
try{
this.servSocket = new ServerSocket(port);
System.out.println("Server socket established");
}
catch (IOException ex){
System.out.println("Unable to establish server socket. Code pink \n");
ex.printStackTrace();
}
And after the above comes this:
public void waitForClients(){
System.out.println("The gates has been opened...");
while (true){
try {
Socket client = servSocket.accept();
processClient(client);
}
catch (IOException ex){
ex.printStackTrace();
}
}
}
private void processClient(Socket client){
writers.add(getClientWriter(client));
startUpdateFrom(client);
System.out.println("New client connected: " + client.getPort());
}
private PrintWriter getClientWriter(Socket client){
try{
return new PrintWriter(client.getOutputStream());
}
catch (Exception ex){
ex.printStackTrace();
}
return null;
}
And finally, a new thread starts to listen to any new messages from that client:
private void startUpdateFrom(Socket client){
new Thread(
new WaitAndSendToAllFrom(client))
.start();
}
Which is:
public class WaitAndSendToAllFrom implements Runnable{
BufferedReader reader;
public WaitAndSendToAllFrom(Socket clientSocket){
try{
reader = new BufferedReader(
new InputStreamReader(
clientSocket.getInputStream()));
}
catch (IOException ex){
ex.printStackTrace();
}
}
public void run(){
try{
String message;
System.out.println("Thread: waiting for messages to send...");
while (true){
message = reader.readLine();
while (message != null){
System.out.println("Server: Sending message: " + message);
sendToAll(message);
}
}
}
catch (IOException ex){
ex.printStackTrace();
}
}
private void sendToAll(String message){
List<PrintWriter> writers = ServerClientConnector.getWriters();
for (PrintWriter pr : writers){
pr.println(message + "\n");
pr.flush();
}
}
}
The cycle gets to the "Thread: waiting for messages to send...", but not any further, reader.readLine() returns null (checked with a sysout :) ). I was trying to debug it, but i'm not so experienced in programing so much, especially debugging two separate codes working with each other. I've been looking at this for 3 days, and i'm seriously stuck here.
while (true){
message = reader.readLine();
while (message != null){
System.out.println("Server: Sending message: " + message);
sendToAll(message);
}
}
This makes no sense. You read one line and then keep testing. It for null in a loop in which it can never change.
A proper way to write this is:
while ((message = reader.readLine()) != null){
System.out.println("Server: Sending message: " + message);
sendToAll(message);
}
I'm new with Java and I'm trying to learn threads and socket. So decide to make simple client-server application following official java tutorial. My idea is simple - server wait for connection, if appears, it makes new thread with new socket, input and output. Client side -> make connection; new thread with socket, input, output and stdIn (to read line and after that send it to the server). But something is wrong (don't have any idea why) with my code. The connection is established, there's no exceptions. Could someone explain why doesn't work and how to fix it? Also could you have any suggestions about the code (probably it's not with best practices and things like that):
Client side:
public class Client {
private BufferedReader reader;
private Socket sock;
private PrintWriter writer;
public static void main(String[] args) {
Client client = new Client();
client.go();
}
public void go() {
setUpNetworking();
}
private void setUpNetworking() {
try{
sock = new Socket("127.0.0.1", 5000);
System.out.println("Network established");
ServerThread serverThread= new ServerThread(sock);
serverThread.start();
System.out.println("Type your message: ");
} catch (IOException e) {
System.out.println("Problem with establishing the network: " + e);
}
}
class ServerThread extends Thread {
Socket socket;
PrintWriter out;
BufferedReader in;
BufferedReader stdIn;
ServerThread(Socket socket) {
this.socket = socket;
try{
out = new PrintWriter(socket.getOutputStream());
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
stdIn = new BufferedReader(new InputStreamReader(System.in));
}catch (IOException e) {
System.out.println("Problem with trying to read/write to server: " + e);
}
}
#Override
public void run() {
String fromServer;
String fromClient;
while(true){
try{
if((fromServer = in.readLine()) != null) System.out.println(" " + fromServer);
else if((fromClient = stdIn.readLine()) != null) out.println(fromClient);
}catch(Exception e) {
System.out.println("msg exception: " + e);
}
}
}
}
}
Server side:
public class Server {
//Run server until keepGoing = false
private boolean keepGoing = true;
public static void main(String[] args) {
Server server = new Server();
server.go();
}
public void go() {
try {
ServerSocket serverSocket = new ServerSocket(5000);
while(keepGoing) {
Socket clientSocket = serverSocket.accept();
ClientThread t = new ClientThread(clientSocket);
t.start();
}
} catch (IOException e) {
System.out.println("Problem with socket/network: " + e);
}
}
class ClientThread extends Thread {
Socket clientSocket;
PrintWriter out;
BufferedReader in;
ClientThread(Socket clientSocket) {
this.clientSocket = clientSocket;
try{
out = new PrintWriter(clientSocket.getOutputStream());
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
} catch (IOException e) {
System.out.println("Problem with creating in/out: " + e);
}
}
#Override
public void run() {
String message;
while(keepGoing) {
try{
message = in.readLine();
out.println(message);
System.out.println(message);
} catch (IOException e){
System.out.println("Exception while try to read line: " + e);
}
}
}
}
}
PS I've changed a bit the code - instead of made ClientThread Class, I made new runnable class and pass that variable to thread class. Inspired by this question: "implements Runnable" vs. "extends Thread".
I think the problem is that both server and client are waiting for any input. Server:
message = in.readLine();
Client:
if((fromServer = in.readLine()) != null)
System.out.println(" " + fromServer);
else if((fromClient = stdIn.readLine()) != null)
out.println(fromClient);
But the client code already blocks on the fromServer = in.readLine() part, so it never gets to read from standard in, and thus nothing will be sent out to the server.
You could move your attempt to read from standard in to the setUpNetworking method, right after the System.out.println("Type your message: ");. Build a loop there which you exit if the user types "exit" or "quit" or something like that:
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
String read = "";
do {
read = stdIn.readLine();
System.out.println("Read from stdin: " + read);
serverThread.send(read);
}
while (!read.equals("exit"));
The ServerThread.send() method is simple:
void send(String string) {
System.out.println("Sending to server: " + string);
out.println(string);
}
However, to make it work, you either have to flush the stream manually after writing to out, or use the following constructor:
out = new PrintWriter(socket.getOutputStream(), true);
See the PrintWriter's JavaDoc: True means auto-flush on newline.
I tested this setup and it worked for me. I was able to send something from the client to the server.
However, this is only the first step. I would implement both reading and writing as separate threads, for both client and server. And there is no graceful shutdown of sockets implemenented yet. A more complete yet simple example can be found on Oracle.
Hello I need some quick help with this Server/Client socket program I am writing in Java. Everything works as intended when entering standard input on the client side. The server responds with the correct data every time. But when I send data to the Server using the actionListener, nothing is returned. The data is being sent over and read by the Server and can be printed server-side, it just won't come back to the Client.
So this must be an issue with the formatting or type of data being sent from the actionListener (I don't know enough about streams unfortunately), or it is an issue with the stream on the server side?
Any help is most appreciated!
public class Serv {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(8889);
System.out.println("Waiting for client...");
} catch (IOException e) {
System.err.println("Could not listen on port: 8889.");
System.exit(1);
}
Socket clientSocket = serverSocket.accept();
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
String inputLine, outputLine;
Protocol p = new Protocol();
out.println("welcome");
while ((inputLine = in.readLine()) != null) {
outputLine = p.processInput(inputLine);
System.out.println("Input: "+inputLine + "\nOutput: "+outputLine);
out.println(outputLine);
if (outputLine.equals("Exit")) { break; }
}
out.close();
in.close();
clientSocket.close();
serverSocket.close();
}
}
public class Cl extends JFrame {
public static PrintWriter out = null;
public static String fromUser;
public static void Client() {
saveAnswer.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ButtonModel b = group.getSelection();
if (b.getActionCommand() == "A") { sendAnswer = radioA.getText(); }
if (b.getActionCommand() == "B") { sendAnswer = radioB.getText(); }
if (b.getActionCommand() == "C") { sendAnswer = radioC.getText(); }
String data = "÷" + sendAnswer;
out.println(data);
}
});
}
public static void main(String[] args) throws IOException {
Socket Socket = null;
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
boolean checkOpen = false;
Socket clientS = new Socket("localhost", 8889);
out = new PrintWriter(clientS.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(clientS.getInputStream()));
String fromServer;
while ((fromServer = in.readLine()) != null) {
if (fromServer.startsWith("®")) {
if (checkOpen == false) { Cl.Client(); checkOpen = true; }
qA.splitter(fromServer);
}
if (fromServer.equals("Exit")) { break; }
fromUser = stdIn.readLine();
if (fromUser != null) {
System.out.println("Client: " + fromUser);
out.println(fromUser);
}
else { System.out.println("trouble"); }
}
out.close();
in.close();
stdIn.close();
Socket.close();
}
}
In the server, you're sending one line and then reading from the client until EOS.
In the client, you're reading from the server until EOS and then sending whatever the user types.
Your protocol doesn't make sense. All you have here is a deadlock.
You might need to do out.flush() after writing the response on the server side.
I am creating a program where multiple clients can connect to a server. The message sent by a client will be broadcast to all other client connections on the server.
My problem is that the message is broadcast to only the client it has come from, and I cannot spot the error in my code.
Can anyone help me spot where the problem is or how I could improve the code?Thank you.
EDIT:
public class MsgClient{
private Socket client;
private ObjectInputStream input;
private DataOutputStream output;
private BufferedReader keyboard;
private String cmdInput;
public MsgClient(String name, String server, int port){
try{
client = new Socket(server, port);
DataInputStream sInput = new DataInputStream(client.getInputStream());
output = new DataOutputStream(client.getOutputStream());
input = new ObjectInputStream(client.getInputStream());
keyboard = new BufferedReader(new InputStreamReader(System.in));
output.writeUTF(name);
while(true){
System.out.println("Send a msg to the server: ");
cmdInput = keyboard.readLine();
output.writeUTF(cmdInput);
System.out.println(sInput.readUTF());
}
}
catch (Exception e){
e.printStackTrace();
}
}// end constructor
public static void main(String args[]) throws IOException {
if(args.length != 3)
throw new RuntimeException("Syntax: java MsgClient <username> <servername> <port>");
MsgClient aClient = new MsgClient(args[0], args[1], Integer.parseInt(args[2]));
} // end main
}
public class MsgServer {
public MsgServer(int PORT) throws IOException{
ServerSocket server = new ServerSocket(PORT);
System.out.println("Server Established...");
while(true){
Socket client = server.accept();
DataInputStream input = new DataInputStream(client.getInputStream());
ObjectOutputStream oo = new ObjectOutputStream(client.getOutputStream());
DataOutput output = new DataOutputStream(client.getOutputStream());
System.out.println("New client accepted");
String clientName = input.readUTF();
ClientHandler handler = new ClientHandler(clientName, client); // construct and run thread.
handler.start();
System.out.println("Handler started!");
}//end while
}//end of constructor
public static void main(String args[]) throws IOException {
if(args.length != 1)
throw new RuntimeException("Syntax: java MsgServer requires <PORT> number");
new MsgServer(Integer.parseInt(args[0]));
}
}
public class ClientHandler extends Thread {
Socket client;
DataInputStream din;
DataOutputStream dout;
String name;
String clientMsg;
protected static Vector socketVector = new Vector();
public ClientHandler (String name, Socket client) throws IOException{
this.name = name;
this.client = client;
din = new DataInputStream(client.getInputStream());
dout = new DataOutputStream(client.getOutputStream());
}
// Code run at every start()
public void run(){
try{
socketVector.addElement(this);
clientMsg = din.readUTF(); // inside or outside loop?
while(true){
broadcast( name + " has joined auction on IP " + client.getInetAddress());
broadcast( name + " says: " + clientMsg);
}
} catch(IOException ex){
System.out.println("-- Connection to user lost");
} finally{
socketVector.removeElement(this);
broadcast(name + " has left");
try{
client.close();
}catch (IOException ex){
System.out.println("socket to user already closed?");
}
}
}
Another issue is here, in the MsgClient code:
cmdInput = keyboard.readLine();
output.writeUTF(cmdInput);
System.out.println(sInput.readUTF());
A client will not receive a message until after it has sent one.
Where is the broadcast() method?
You are creating two sets of streams in the server. The accept loop shouldn't create any streams or do any I/O. All that should be done in the thread that handles the connection.
You don't need the ObjectInput/OutputStreams at all here.
When you get any IOException other than a read timeout on a socket you must close it. You should also print out the exception's own message, rather than just making up your own.