I am attempting to make a chatroom as my first program that communicates between computers. I am having trouble setting up the Server Socket Though. My program stops when it tries to set up.

Here are my variables

private JTextField textArea;
	private ServerSocket servSock;
	private Socket sock;
	private BufferedReader buff;
	private PrintStream output;
	private String allMessages;
	private JTextArea messages;
	private String user;

I call this code

private void setUpServer() {
		// TODO Auto-generated method stub
		System.out.println ("Seting up Server");
		try {
			servSock = new ServerSocket (9999);
			sock = servSock.accept();
			buff = new BufferedReader (new InputStreamReader (sock.getInputStream()));
			output = new PrintStream (sock.getOutputStream());
			System.out.println ("Trying");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.out.println ("failed");
		}
		
	}

It prints out "Setting up Server" and then it freezes. It doesn't give me any errors or anything. What is the problem?

Thanks for your help

"sock = servSock.accept();"

... That's a blocking call. Your coding is awaiting someone to connect on port 9999. Telnet to that port and your code will continue. (telnet 127.0.0.1 9999)

I don't have a serveSock.close (); statement. is there any way to rewire the x button on the frame to close the server before it exits the frame?

OK. Thanks for the help with the window. Because of not having the servSock.close(); in my code the server is till running in the background. is there any way to reset, stop the server from running, because I currently get this error

java.net.BindException: Address already in use: JVM_Bind
	at java.net.PlainSocketImpl.socketBind(Native Method)
	at java.net.PlainSocketImpl.bind(Unknown Source)
	at java.net.ServerSocket.bind(Unknown Source)
	at java.net.ServerSocket.<init>(Unknown Source)
	at java.net.ServerSocket.<init>(Unknown Source)
	at Chatroom.setUpServer(Chatroom.java:107)
	at Chatroom.<init>(Chatroom.java:26)
	at Chatroom.main(Chatroom.java:128)

Thanks

You'll have to kill the process. Look for your program running in the task manager or process manager and end the process. (ctrl-alt-del task manager in windows or ps in linux)

I am not getting anything on the text fields. Here is my server code

import java.awt.event.*;
import java.awt.*;
import javax.swing.*;

import java.io.*;
import java.net.*;
import java.nio.*;

public class Chatroom implements ActionListener, WindowListener {

	
	private JTextField textArea;
	private ServerSocket servSock;
	private Socket sock;
	private BufferedReader buff;
	private PrintStream output;
	private String allMessages;
	private JTextArea messages;
	private String user;
	
	private Chatroom (){
				
		user = JOptionPane.showInputDialog(null, "Enter your Nickname", "Nickname Info", JOptionPane.INFORMATION_MESSAGE);
		System.out.println ("Got Nickname");
		
		System.out.println ("Setting up GUI");
		
		JFrame frame = new JFrame ("Warrior Productions Chat"); frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE); frame.addWindowListener(this);
		JPanel pane = new JPanel ();
		
		pane.setLayout(new GridBagLayout ());
		GridBagConstraints c = new GridBagConstraints();
		c.anchor = GridBagConstraints.FIRST_LINE_START;
		//JPanel chatArea = new JPanel ();
		//JPanel messageArea = new JPanel();
		//JPanel onArea = new JPanel();
		
		//Titles
		
		JLabel chatTitle = new JLabel ("ChatRoom:");
		c.gridx = 0;
		c.gridy = 0;
		pane.add (chatTitle,c);
		
		JLabel usersTitle = new JLabel ("Users:");
		c.gridx = 2;
		c.gridy = 0;
		pane.add (usersTitle,c);
		//end titles, begin GUI
		
		
		textArea = new JTextField (40);     // enter message
		c.gridx = 0;
		c.gridy = 3;
		
		pane.add(textArea,c);
		//JPanel sendButtonArea = new JPanel ();
		
		JButton send = new JButton ("Send");send.setActionCommand ("send");send.addActionListener(this);
		c.gridx = 1;
		c.gridy = 3;
		send.setPreferredSize(new Dimension (75,25));
		pane.add (send,c);
		
		JTextArea users = new JTextArea (20,10);          // SET THE USERS 
		c.gridx = 2;
		c.gridy = 1;
		
		users.setEditable (false);
		
		pane.add(users,c);
		messages = new JTextArea (20,40);       // see messages 
		c.gridx = 0;
		c.gridy = 1;
		
		messages.setEditable(false);
		pane.add (messages, c);
				
		
		//chatArea.add(messages);onArea.add(users);messageArea.add(textArea); sendButtonArea.add(send);
		
		//pane.add (chatArea); pane.add (onArea); pane.add(messageArea);pane.add (sendButtonArea);
		
		
		frame.add(pane);
		
		
		
		frame.setSize (700,400);
		frame.setResizable(true);
		frame.setVisible(true);
		System.out.println ("GUI Done. Creating timer");
		
		setUpServer();
		
		Timer timer = new Timer (100,this); timer.setActionCommand ("timer");
		System.out.println ("timer Created");
	}
	
	
	
	
	
	
	private void setUpServer() {
		// TODO Auto-generated method stub
		System.out.println ("Seting up Server");
		try {
			servSock = new ServerSocket (9999);
			sock = servSock.accept();
			buff = new BufferedReader (new InputStreamReader (sock.getInputStream()));
			output = new PrintStream (sock.getOutputStream());
			System.out.println ("Trying");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			
			System.out.println ("failed");
		}
		
	}






	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Chatroom cr = new Chatroom ();
	}






	@Override
	public void actionPerformed(ActionEvent e) {
		// TODO Auto-generated method stub
		if ("send".equals(e.getActionCommand())){
			// send message to other person
			sendMessage ();
			
		}
		if ("timer".equals (e.getActionCommand())){
			try {
				String incomeMessage = buff.readLine();
				if (incomeMessage != null){
					allMessages += "/n" + incomeMessage;
					messages.setText (allMessages);
				}
				
			} catch (IOException s) {
				// TODO Auto-generated catch block
				s.printStackTrace();
			}
		}
		
	}




	
	
	private void sendMessage() {
		// TODO Auto-generated method stub
		System.out.println ("Sending Message");
		String message = textArea.getText();
		textArea.setText("");
		output.print(user + ": " + message);
		System.out.println ("Message Sent");
	}






	@Override
	public void windowActivated(WindowEvent arg0) {
		// TODO Auto-generated method stub
		
	}






	@Override
	public void windowClosed(WindowEvent arg0) {
		// TODO Auto-generated method stub
		System.out.println ("Window Closing (Closed)");
		try {
			servSock.close();
			System.out.println ("Socket Closed");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}






	@Override
	public void windowClosing(WindowEvent arg0) {
		// TODO Auto-generated method stub
		System.out.println ("Window Closing (Closing)");
		try {
			servSock.close();
			System.out.println ("Socket Closed");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.out.println ("Failed to close Socket");
		}
	}






	@Override
	public void windowDeactivated(WindowEvent arg0) {
		// TODO Auto-generated method stub
		
	}






	@Override
	public void windowDeiconified(WindowEvent arg0) {
		// TODO Auto-generated method stub
		
	}






	@Override
	public void windowIconified(WindowEvent arg0) {
		// TODO Auto-generated method stub
		
	}






	@Override
	public void windowOpened(WindowEvent arg0) {
		// TODO Auto-generated method stub
		
	}

}

I am not sure where I am going wrong. I am attempting to check every 100 ms if a new message has been sent, and if it has then it should make a new line and print the message on the screen, but it doesn't. It says that the message is sent, so that works. It is just the printing to the screen.

I modified my code, and now It prints on the screen. Now my only problem is connecting between the two. Am I able to use the timer to see if the other user sent a message, or will this mess everything up. How would I continuously check if the person has sent a message?

How would I continuously check if the person has sent a message?

Is this on the sending side or the receiving side?
Why not have the side that you want to know of their activity post a message saying they have sent/received the message?

This is the code that should check for the message.

if ("timer".equals (e.getActionCommand())){
			try {
				String incomeMessage = buff.readLine();
				if (incomeMessage != null){
					System.out.println ("Message recieved");
					allMessages += "/n" + incomeMessage;
					messages.setText (allMessages);
					incomeMessage = null;
				}
				
			} catch (IOException s) {
				// TODO Auto-generated catch block
				s.printStackTrace();
			}
		}

When I sent the message the client should print out that it received the message in its console window, but it didn't.

Currently I am sending form my Server to my Client.

Both codes are very similar.

A problem with your posted code is that the ServerSocket blocks until it gets a connection. You need to put the ServerSocket code in its own thread.
That thread can read and post what it receives after a connection. No need for a timer to attempt reads. Let the server thread do the reads.
Later you will want to have another thread to do the reads for each connect so that the server can handle more than one client concurrently by spawning a thread to read the current connection and then looping back to issue another accept() to wait for the next connection.

I tried to include a thread. Here is the server code

import java.awt.event.*;
import java.awt.*;
import javax.swing.*;

import java.io.*;
import java.net.*;
import java.nio.*;

public class Chatroom implements ActionListener, WindowListener, Runnable {

	
	private JTextField textArea;
	private ServerSocket servSock;
	private Socket sock;
	private BufferedReader buff;
	private PrintStream output;
	private String allMessages = "Welcome to the Chat Room";
	private JTextArea messages;
	private String user;
	
	private Chatroom (){
		JFrame frame = new JFrame (""); frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE); frame.addWindowListener(this);
		user = JOptionPane.showInputDialog(null, "Enter your Nickname", "Nickname Info - Server", JOptionPane.INFORMATION_MESSAGE);
		if (user == null){
			randomAssignUser ();
		}
		frame.setTitle ("Chat Server - " + user);
		
		System.out.println ("Got Nickname");
		
		System.out.println ("Setting up GUI");
		
		JPanel pane = new JPanel ();
		
		pane.setLayout(new GridBagLayout ());
		GridBagConstraints c = new GridBagConstraints();
		c.anchor = GridBagConstraints.FIRST_LINE_START;
		//JPanel chatArea = new JPanel ();
		//JPanel messageArea = new JPanel();
		//JPanel onArea = new JPanel();
		
		//Titles
		
		JLabel chatTitle = new JLabel ("ChatRoom:");
		c.gridx = 0;
		c.gridy = 0;
		pane.add (chatTitle,c);
		
		JLabel usersTitle = new JLabel ("Users:");
		c.gridx = 2;
		c.gridy = 0;
		pane.add (usersTitle,c);
		//end titles, begin GUI
		
		
		textArea = new JTextField (40);     // enter message
		c.gridx = 0;
		c.gridy = 3;
		
		pane.add(textArea,c);
		//JPanel sendButtonArea = new JPanel ();
		
		JButton send = new JButton ("Send");send.setActionCommand ("send");send.addActionListener(this);
		c.gridx = 1;
		c.gridy = 3;
		send.setPreferredSize(new Dimension (75,25));
		pane.add (send,c);
		
		JTextArea users = new JTextArea (20,10);          // SET THE USERS 
		c.gridx = 2;
		c.gridy = 1;
		
		users.setEditable (false);
		
		pane.add(users,c);
		messages = new JTextArea (20,40);       // see messages 
		c.gridx = 0;
		c.gridy = 1;
		messages.setText (allMessages);
		messages.setEditable(false);
		pane.add (messages, c);
				
		
		//chatArea.add(messages);onArea.add(users);messageArea.add(textArea); sendButtonArea.add(send);
		
		//pane.add (chatArea); pane.add (onArea); pane.add(messageArea);pane.add (sendButtonArea);
		
		
		frame.add(pane);
		
		
		
		frame.setSize (700,400);
		frame.setResizable(true);
		frame.setVisible(true);
		System.out.println ("GUI Done. Creating Thread");
		
		setUpServer();
		
		Thread thread = new Thread ();
		thread.start ();
		System.out.println ("Thread created and Started");
	}
	




	private void setUpServer() {
		// TODO Auto-generated method stub
		System.out.println ("Seting up Server");
		try {
			servSock = new ServerSocket (9999);
			sock = servSock.accept();
			buff = new BufferedReader (new InputStreamReader (sock.getInputStream()));
			output = new PrintStream (sock.getOutputStream());
			System.out.println ("Trying");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			
			System.out.println ("failed");
		}
		
	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Chatroom cr = new Chatroom ();
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		// TODO Auto-generated method stub
		if ("send".equals(e.getActionCommand())){
			// send message to other person
			sendMessage ();
			
		}			
		
	}
	
	
	private void sendMessage() {
		// TODO Auto-generated method stub
		System.out.println ("Sending Message");
		String message = textArea.getText();
		message = user + ": " + message;
		output.print(message);
		allMessages += " \n " + message;
		messages.setText (allMessages);
		textArea.setText("");
		
		System.out.println ("Message Sent");
	}



	@Override
	public void windowActivated(WindowEvent arg0) {
		// TODO Auto-generated method stub
		
	}


	@Override
	public void windowClosed(WindowEvent arg0) {
		// TODO Auto-generated method stub 
	}


	@Override
	public void windowClosing(WindowEvent arg0) {
		// TODO Auto-generated method stub
		System.out.println ("Window Closing (Closing)");
		try {
			servSock.close();
			System.out.println ("Socket Closed");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.out.println ("Failed to close Socket");
		}
	}


	@Override
	public void windowDeactivated(WindowEvent arg0) {
		// TODO Auto-generated method stub
		
	}


	@Override
	public void windowDeiconified(WindowEvent arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void windowIconified(WindowEvent arg0) {
		// TODO Auto-generated method stub
		
	}



	@Override
	public void windowOpened(WindowEvent arg0) {
		// TODO Auto-generated method stub
		
	}

	private void randomAssignUser() {
		// TODO Auto-generated method stub
		int random = (int) Math.round (Math.random () * 100);
		
		if (random < 10){
			user = "LameFace";
		}
		else if (random < 20){
			user = "ICan'tRead";
		}
		else if (random < 30){
			user = "Guest";
		}
		else if (random < 40){
			user = "NoName";
		}
		else if (random < 50){
			user = "Brain";
		}
		else if (random < 60){
			user = "Noob";
		}
		else if (random < 70){
			user = "Lame";
		}
		else if (random < 80){
			user = "Caligula";
		}
		else if (random < 90){
			user = "Me";
		}
		else if (random < 99){
			user = "Wow";
		}
		else if (random == 100){
			user = "Jesus";
		}
		
		int randomNum = (int)Math.random() * 100;
		user += "" + randomNum;
		
		
	}


	@Override
	public void run() {
		// TODO Auto-generated method stub
		try {
			String incomeMessage = buff.readLine();
			if (incomeMessage != null){
				System.out.print("Setting Text");
				allMessages += "/n" + incomeMessage;
				messages.setText (allMessages);
				incomeMessage = null;
				System.out.print("Text Set");
			}
			
		} catch (IOException s) {
			// TODO Auto-generated catch block
			s.printStackTrace();
		}
	
		
		
	}
}

and here is the client code:

import java.awt.event.*;
import java.awt.*;
import javax.swing.*;

import java.io.*;
import java.net.*;
import java.nio.*;



public class ChatroomClient implements ActionListener, WindowListener, Runnable {

	
	private JTextField textArea;
	private Socket sock;
	private BufferedReader buff;
	private PrintStream output;
	private String allMessages = "Welcome to the Chat Room";
	private JTextArea messages;
	private String user;
	
	private ChatroomClient (){
		
		JFrame frame = new JFrame (""); frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE); frame.addWindowListener(this);
		
		user = JOptionPane.showInputDialog(null, "Enter your Nickname", "Nickname Info - Client", JOptionPane.INFORMATION_MESSAGE);
		System.out.println(user);
		if (user == null){
			randomAssignUser ();
		}
		frame.setTitle ("Chat Client - " + user);
		
		setUpClient();
		
		
		
		
		JPanel pane = new JPanel ();
		
		pane.setLayout(new GridBagLayout ());
		GridBagConstraints c = new GridBagConstraints();
		c.anchor = GridBagConstraints.FIRST_LINE_START;
		//JPanel chatArea = new JPanel ();
		//JPanel messageArea = new JPanel();
		//JPanel onArea = new JPanel();
		
		//Titles
		
		JLabel chatTitle = new JLabel ("ChatRoom:");
		c.gridx = 0;
		c.gridy = 0;
		pane.add (chatTitle,c);
		
		JLabel usersTitle = new JLabel ("Users:");
		c.gridx = 2;
		c.gridy = 0;
		pane.add (usersTitle,c);
		//end titles, begin GUI
		
		
		textArea = new JTextField (40);     // enter message
		c.gridx = 0;
		c.gridy = 3;
		
		pane.add(textArea,c);
		//JPanel sendButtonArea = new JPanel ();
		
		JButton send = new JButton ("Send");send.setActionCommand ("send");send.addActionListener(this);
		c.gridx = 1;
		c.gridy = 3;
		send.setPreferredSize(new Dimension (75,25));
		pane.add (send,c);
		
		JTextArea users = new JTextArea (20,10);          // SET THE USERS 
		c.gridx = 2;
		c.gridy = 1;
		
		users.setEditable (false);
		
		pane.add(users,c);
		messages = new JTextArea (20,40);       // see messages 
		c.gridx = 0;
		c.gridy = 1;
		
		messages.setEditable(false);
		messages.setText (allMessages);
		pane.add (messages, c);
				
		
		//chatArea.add(messages);onArea.add(users);messageArea.add(textArea); sendButtonArea.add(send);
		
		//pane.add (chatArea); pane.add (onArea); pane.add(messageArea);pane.add (sendButtonArea);
		
		
		frame.add(pane);
		
		
		
		frame.setSize (700,400);
		frame.setResizable(true);
		frame.setVisible(true);
		
		Thread thread = new Thread ();
		thread.start();
		
	}
	
	private void randomAssignUser() {
		// TODO Auto-generated method stub
		int random = (int) Math.round (Math.random () * 100);
		
		if (random < 10){
			user = "LameFace";
		}
		else if (random < 20){
			user = "ICan'tRead";
		}
		else if (random < 30){
			user = "Guest";
		}
		else if (random < 40){
			user = "NoName";
		}
		else if (random < 50){
			user = "Brain";
		}
		else if (random < 60){
			user = "Noob";
		}
		else if (random < 70){
			user = "Lame";
		}
		else if (random < 80){
			user = "Caligula";
		}
		else if (random < 90){
			user = "Me";
		}
		else if (random < 99){
			user = "Wow";
		}
		else if (random == 100){
			user = "Jesus";
		}
		
		int randomNum = (int)Math.random() * 100;
		user += "" + randomNum;
		
		
	}

	private String host = "localHost"; 
	private int port = 9999;
	
	private void setUpClient() {
		// TODO Auto-generated method stub
		try {
			sock = new Socket (host,port);
			buff = new BufferedReader (new InputStreamReader (sock.getInputStream()));
			output = new PrintStream (sock.getOutputStream());
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
	}


	public static void main(String[] args) {
		// TODO Auto-generated method stub
		ChatroomClient cc = new ChatroomClient ();
	}


	@Override
	public void actionPerformed(ActionEvent e) {
		// TODO Auto-generated method stub
		if ("send".equals(e.getActionCommand())){
			// send message to other person
			sendMessage ();
			
		}
	}


	private void sendMessage() {
		// TODO Auto-generated method stub
		String message = textArea.getText();
		if (message != null){
			System.out.println ("Sending Message");
			textArea.setText("");
			message = user + ": " + message;
			output.print(message);
			allMessages += " \n " + message;
			messages.setText (allMessages);
			System.out.println ("Message Sent");
		}
	}


	@Override
	public void windowActivated(WindowEvent e) {
		// TODO Auto-generated method stub
		
	}


	@Override
	public void windowClosed(WindowEvent e) {
		// TODO Auto-generated method stub
		
	}


	@Override
	public void windowClosing(WindowEvent e) {
		// TODO Auto-generated method stub
		try {
			sock.close();
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
			System.out.println ("Failed to Close Socket");
		}
	}


	@Override
	public void windowDeactivated(WindowEvent e) {
		// TODO Auto-generated method stub
		
	}


	@Override
	public void windowDeiconified(WindowEvent e) {
		// TODO Auto-generated method stub
		
	}


	@Override
	public void windowIconified(WindowEvent e) {
		// TODO Auto-generated method stub
		
	}


	@Override
	public void windowOpened(WindowEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void run() {
		// TODO Auto-generated method stub
		try {
			String incomeMessage = buff.readLine();
			if (incomeMessage != null){
				System.out.println ("Message recieved");
				allMessages += "/n" + incomeMessage;
				messages.setText (allMessages);
				incomeMessage = null;
			}
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}

I am still not getting messages from one to the other

Thread thread = new Thread ();
		thread.start ();
		System.out.println ("Thread created and Started");

If this is Your thread, it does nothing.

it starts

public void run (){

}

at 260 on the client and 260 on the server

How is that run() method used? Where/when does any code call it?

I forgot the this in the creation of the thread. that should then fix the problem of the thread not starting

The SocketServer should be in the thread.
And the same on the client. The code to communicate with the server should be on a separate thread from the GUI so that the cient can receive a message when the server sends it.

do you mean that I should move my setUpServer and setUpClient methods to the thread?

I already moved the receiving portion of my code to the thread

For the server

public void run() {
		// TODO Auto-generated method stub

		System.out.println ("In Thread");
		try {
			String incomeMessage = buff.readLine();
			if (incomeMessage != null){
				System.out.print("Setting Text");
				allMessages += "/n" + incomeMessage;
				messages.setText (allMessages);
				incomeMessage = null;
				System.out.print("Text Set");
			}

		} catch (IOException s) {
			// TODO Auto-generated catch block
			s.printStackTrace();
		}


		


	}

For the client

public void run() {
		// TODO Auto-generated method stub
		try {
			String incomeMessage = buff.readLine();
			if (incomeMessage != null){
				System.out.println ("Message recieved");
				allMessages += "/n" + incomeMessage;
				messages.setText (allMessages);
				incomeMessage = null;
			}
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

move my setUpServer and setUpClient methods to the thread?

That would be a start.

the receiving portion of my code

Neither of them have loops. Do you only want to receive one message?

I moved the setups to the thread. I am still not getting a message through though.

How do you read a message? What method do you use? When will that method return a String? Read the API doc for the method to see what it does.

I use this

String incomeMessage = buff.readLine();

to read the incoming message. It returns a string.

When will that method return a String? Read the API doc for the method to see what it does. Did you read the doc to see ALL the requirements for the String that is read? Like what determines the end of the String.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.