So I decided to try and create a simple chat room type of program. I've got most of the things working, when I send a message, it outputs on the server.. Except I can only send one message, after that nothing happens on the server.?
i.e: input on client: "Hello world!"
output on server: "Hello world!"
I then try to send another message: input on client: "Mr. Server, why u so random?"
output on server: null (it doesn't say null it just doesn't do anything at all)
What could be the cause of this?
Client:
public class ClientSocket {
final static int PORT = 5921;
public static void main(String[] args) throws IOException
{
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 200);
JPanel panel = new JPanel();
final JTextField field = new JTextField(20);
JLabel l = new JLabel("Enter a message and see it on the server...");
panel.add(field);
panel.add(l);
frame.add(panel);
frame.setVisible(true);
final Socket sock = new Socket("90.231.151.132", PORT);
final PrintStream ps = new PrintStream(sock.getOutputStream());
field.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
String txt = field.getText();
ps.println(txt);
ps.close();
field.setText("");
}
});
}
}
Server:
public class ServerSocketTest
{
final static int PORT = 5921;
public static void main(String[] args) throws Exception
{
ServerSocketTest t = new ServerSocketTest();
t.run();
}
public void run() throws Exception
{
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 200);
JPanel panel = new JPanel();
final JTextArea field = new JTextArea(5, 20);
JButton button = new JButton("Close connection");
field.setEditable(false);
JLabel l = new JLabel("Messages coming from the client is displayed here..");
panel.add(field);
panel.add(l);
panel.add(button);
frame.add(panel);
//frame.add(l);
frame.setVisible(true);
final ServerSocket servSock = new ServerSocket(PORT);
while(true){
Socket sock = servSock.accept();
InputStreamReader ir = new InputStreamReader(sock.getInputStream());
BufferedReader br = new BufferedReader(ir);
String r = br.readLine();
br.close();
System.out.println(r);
field.append(r);
button.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent arg0)
{
try {
servSock.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
}
}
From Socket's JavaDoc:
getOutputStream() throws IOException
...
Closing the returned OutputStream will close the associated socket.
When you close the stream you are closing also the socket. The same issue is with your server side implementation. So either you need to open the socket again or actually not close it.