I have followed the newboston tutorials and made a chatroom with server side code and client side code. I wanted to build them together in one app.
My issue is that the client is blank, I used the standalone server from the tutorial.
picture of server chat working with the client chat being a blank window
But if I close the server first, all of the chat appears on the client chat, as in it is all instantly updated.
client chat updated, all previous chats messages displayed.
Standalone server:
package instantmessage;
import javax.swing.JFrame;
public class ServerChatroom {
public static void main(String[] args) {
Server runServer = new Server();
runServer.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
runServer.startServer();
}
}
package instantmessage;
import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Server extends JFrame{
private JTextField userText; //where you type in message
private JTextArea chatWindow; //displays the conversation
private ObjectOutputStream output; //information sent to the recipent
private ObjectInputStream input; //information being received from the recipent
private ServerSocket server;
private Socket connection; //the connection between you and the recipent's computer
//setting up GUI.
public Server(){
super("Instant Messanger - Server"); //the piece in the brackets is the title off the app.
userText = new JTextField();
userText.setEditable(false);//without having a connection you can't send messages.
userText.addActionListener(
new ActionListener(){
#Override
public void actionPerformed(ActionEvent event){
sendMessage(event.getActionCommand()); //sends string that was typed into text field.
userText.setText(""); //after text has been sent, remove the previous message sent.
}
}
);
add(userText, BorderLayout.NORTH); //add userText to GUI, make chat window top of the screen.
chatWindow = new JTextArea();
add(new JScrollPane(chatWindow)); //scrolling pane created for all the chats.
setSize(450,200);
setVisible(true);
}
//create the server and run the serve.
public void startServer(){
try{
server = new ServerSocket(6789, 100); //Server socket. first one the server socket, the second how many clients can wait for connection.
while(true){//the loop should run forever. The main program.
try{//connect and allow conversation with another
waitForConnection();//wait for someone to connect with server.
setupStream(); //create the connection between another computer.
whileChatting(); //allow messages to be sent back and forth during chat.
}catch(EOFException eofException){ //whenever the conversation is ended.
showMessage("\n Server overloaded, connection terminated by the server.");
}finally{
closeServer();
}
}
}catch(IOException ioException){
ioException.printStackTrace();
}
}
//wait for connection, after connection established display connection details.
private void waitForConnection() throws IOException{
showMessage("Waiting for connection to be established...\n"); //so user has something to see, knows program isn't frozen.
connection = server.accept(); //accept the connection.
showMessage("Connection established with " + connection.getInetAddress().getHostName());
}
//gets stream for send/receiving of data.
private void setupStream() throws IOException{
output = new ObjectOutputStream(connection.getOutputStream()); //create pathway for connection to other computer.
output.flush(); //good practice. Cleans up data that was "left over"
input = new ObjectInputStream(connection.getInputStream()); //creates pathway to receive data from other PC.
//no flush for input, the other side has to flash.
showMessage("Connection now active");
}
//sending text back and forth
//this receives the data from the connected computer and displays it.
private void whileChatting() throws IOException{
String message = " You are now connected ";
sendMessage(message);
ableToType(true);
do{//have conversation while client doesn't send CLIENT - END.
try{
message = (String) input.readObject(); //read whatever message is incoming.
showMessage("\n" + message);
}catch(ClassNotFoundException classNotFoundException){
showMessage("\n user has sent garbage.");
}
}while(!message.equals("CLIENT - END"));
}
//close streams/sockets after chat ends. "Good housekeeping". Frees up memory.
private void closeServer(){
showMessage("\n\tTerminating connection...");
ableToType(false);
try{
input.close(); //terminate stream from
output.close(); //terminate stream to
connection.close(); //terminate connection
}catch(IOException ioException){
ioException.printStackTrace();
}
}
//send message to connected computer.
private void sendMessage(String message){
try{
output.writeObject("SERVER - " + message); //creates an object of message and sends it along the output stream.
output.flush(); //remove once it's finished sending.
showMessage("\nSERVER - " + message);
}catch(IOException ioException){
chatWindow.append("\n error sending message"); //print out the error in the chat window that the message was not sent.
}
}
//shows messages on main chat area. Updates the chatWindow so it is always current.
private void showMessage(final String string){
SwingUtilities.invokeLater( //creates thread that updates parts of the GUI.
new Runnable(){
public void run(){
chatWindow.append(string);
}
}
);
}
//sets the textfield editable so that the user can type in it
private void ableToType(final boolean bool){
SwingUtilities.invokeLater( //creates thread that updates parts of the GUI.
new Runnable(){
public void run(){
userText.setEditable(bool);
}
}
);
}
}
My code for the standalone piece:
package chatroomomni;
import javax.swing.JFrame;
public class ChatRoomOmni {
public static void main(String[] args) {
MainMenu runProgram = new MainMenu();
runProgram.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
package chatroomomni;
//the user has to chose to be a client or a server.
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
//layout: first button is host server, second line is a JTextLabel telling user to enter server IP, JTextField next to it for server IP, connect button next.
public class MainMenu extends JFrame{
private JButton hostServer = new JButton("Host server");
private JLabel labelEnterServerIP = new JLabel("Enter Server IP: ");
private JTextField serverIPInput = new JTextField(25);
private JButton connectServer = new JButton("Connect to server");
//constructor
public MainMenu(){
super("Instant Messenger - Main Menu");
serverIPInput.setEditable(true);
//action listener for the host server.
hostServer.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent event){
Server runServer = new Server();
runServer.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
CloseFrame();
runServer.startServer();
}
});
//action listener for connect to server.
connectServer.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent event){
if(!String.valueOf(serverIPInput.getText()).equals("")){
System.out.println(String.valueOf(serverIPInput.getText()));
Client client = new Client(String.valueOf(serverIPInput.getText()));
client.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
CloseFrame();
client.startClient();
}
}
});
setLayout(new FlowLayout());
//add items to frame.
add(hostServer);
add(labelEnterServerIP);
add(serverIPInput);
add(connectServer);
setSize(1000, 500);
setVisible(true);
}
public void CloseFrame(){
super.dispose();
}
}
package chatroomomni;
import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Client extends JFrame{
private JTextField userText; //where you type in message
private JTextArea chatWindow; //displays the conversation
private ObjectOutputStream output; //information sent to the recipent
private ObjectInputStream input; //information being received from the recipent
private Socket connection; //the connection between you and the recipent's computer
private String message;
private String serverIP;
public Client(String host){
super("Instant Messenger - Client");
serverIP = host;
userText = new JTextField();
userText.setEditable(false);
userText.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent event){
sendMessage(event.getActionCommand());
userText.setText("");
}
});
add(userText, BorderLayout.NORTH);
chatWindow = new JTextArea();
add(new JScrollPane(chatWindow), BorderLayout.CENTER);
setSize(500, 400);
setVisible(true);
}
//connect to the server,
public void startClient(){
try{
connectToServer();
setupStream();
whileChatting();
}catch(EOFException eofException){
showMessage("\n Client terminated the connection");
}catch(IOException ioException){
ioException.printStackTrace();
}finally{
closeClient();
}
}
private void connectToServer() throws IOException{
showMessage("Attempting to connect to server...\n");
connection = new Socket(InetAddress.getByName(serverIP), 6789);
showMessage("Connection established to: " + connection.getInetAddress().getHostAddress());
}
private void setupStream() throws IOException{
output = new ObjectOutputStream(connection.getOutputStream()); //create pathway for connection to other computer.
output.flush(); //good practice. Cleans up data that was "left over"
input = new ObjectInputStream(connection.getInputStream()); //creates pathway to receive data from other PC.
//no flush for input, the other side has to flash.
showMessage("Connection now active");
}
private void whileChatting() throws IOException{
String message = " You are now connected ";
sendMessage(message);
ableToType(true);
do{//have conversation while server doesn't send SERVER - END.
try{
message = (String) input.readObject(); //read whatever message is incoming.
showMessage("\n" + message);
}catch(ClassNotFoundException classNotFoundException){
showMessage("\n server has sent garbage.");
}
}while(!message.equals("SERVER - END") || !message.equals("SERVER - TERMINATE CONNECTION"));
}
private void closeClient(){
showMessage("\n\tTerminating connection...");
ableToType(false);
try{
input.close(); //terminate stream from
output.close(); //terminate stream to
connection.close(); //terminate connection
}catch(IOException ioException){
ioException.printStackTrace();
}
}
private void sendMessage(final String message){
try{
output.writeObject("CLIENT - " + message); //creates an object of message and sends it along the output stream.
output.flush(); //remove once it's finished sending.
showMessage("\nCLIENT - " + message);
}catch(IOException ioException){
chatWindow.append("\n error sending message"); //print out the error in the chat window that the message was not sent.
}
}
private void showMessage(final String string){
SwingUtilities.invokeLater( //creates thread that updates parts of the GUI.
new Runnable(){
public void run(){
chatWindow.append(string);
}
}
);
}
private void ableToType(final boolean bool){
SwingUtilities.invokeLater( //creates thread that updates parts of the GUI.
new Runnable(){
public void run(){
userText.setEditable(bool);
}
}
);
}
}
package chatroomomni;
import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Server extends JFrame{
private JTextField userText; //where you type in message
private JTextArea chatWindow; //displays the conversation
private ObjectOutputStream output; //information sent to the recipent
private ObjectInputStream input; //information being received from the recipent
private ServerSocket server;
private Socket connection; //the connection between you and the recipent's computer
//setting up GUI.
public Server(){
super("Instant Messanger - Server"); //the piece in the brackets is the title off the app.
userText = new JTextField();
userText.setEditable(false);//without having a connection you can't send messages.
userText.addActionListener(
new ActionListener(){
#Override
public void actionPerformed(ActionEvent event){
sendMessage(event.getActionCommand()); //sends string that was typed into text field.
userText.setText(""); //after text has been sent, remove the previous message sent.
}
}
);
add(userText, BorderLayout.NORTH); //add userText to GUI, make chat window top of the screen.
chatWindow = new JTextArea();
add(new JScrollPane(chatWindow)); //scrolling pane created for all the chats.
setSize(450,200);
setVisible(true);
}
//create the server and run the serve.
public void startServer(){
try{
server = new ServerSocket(6789, 100); //Server socket. first one the server socket, the second how many clients can wait for connection.
while(true){//the loop should run forever. The main program.
try{//connect and allow conversation with another
waitForConnection();//wait for someone to connect with server.
setupStream(); //create the connection between another computer.
whileChatting(); //allow messages to be sent back and forth during chat.
}catch(EOFException eofException){ //whenever the conversation is ended.
showMessage("\n Server overloaded, connection terminated by the server.");
}finally{
closeServer();
}
}
}catch(IOException ioException){
ioException.printStackTrace();
}
}
//wait for connection, after connection established display connection details.
private void waitForConnection() throws IOException{
showMessage("Waiting for connection to be established...\n"); //so user has something to see, knows program isn't frozen.
connection = server.accept(); //accept the connection.
showMessage("Connection established with " + connection.getInetAddress().getHostName());
}
//gets stream for send/receiving of data.
private void setupStream() throws IOException{
output = new ObjectOutputStream(connection.getOutputStream()); //create pathway for connection to other computer.
output.flush(); //good practice. Cleans up data that was "left over"
input = new ObjectInputStream(connection.getInputStream()); //creates pathway to receive data from other PC.
//no flush for input, the other side has to flash.
showMessage("Connection now active");
}
//sending text back and forth
//this receives the data from the connected computer and displays it.
private void whileChatting() throws IOException{
String message = " You are now connected ";
sendMessage(message);
ableToType(true);
do{//have conversation while client doesn't send CLIENT - END.
try{
message = (String) input.readObject(); //read whatever message is incoming.
showMessage("\n" + message);
}catch(ClassNotFoundException classNotFoundException){
showMessage("\n user has sent garbage.");
}
}while(!message.equals("CLIENT - END"));
}
//close streams/sockets after chat ends. "Good housekeeping". Frees up memory.
private void closeServer(){
showMessage("\n\tTerminating connection...");
ableToType(false);
try{
input.close(); //terminate stream from
output.close(); //terminate stream to
connection.close(); //terminate connection
}catch(IOException ioException){
ioException.printStackTrace();
}
}
//send message to connected computer.
private void sendMessage(String message){
try{
output.writeObject("SERVER - " + message); //creates an object of message and sends it along the output stream.
output.flush(); //remove once it's finished sending.
showMessage("\nSERVER - " + message);
}catch(IOException ioException){
chatWindow.append("\n error sending message"); //print out the error in the chat window that the message was not sent.
}
}
//shows messages on main chat area. Updates the chatWindow so it is always current.
private void showMessage(final String string){
SwingUtilities.invokeLater( //creates thread that updates parts of the GUI.
new Runnable(){
public void run(){
chatWindow.append(string);
}
}
);
}
//sets the textfield editable so that the user can type in it
private void ableToType(final boolean bool){
SwingUtilities.invokeLater( //creates thread that updates parts of the GUI.
new Runnable(){
public void run(){
userText.setEditable(bool);
}
}
);
}
}
All the netbeans project files uploaded to zippyshare: www116(dot)zippyshare(dot)com/v/qAa5BGWn/file(dot)html (not allowed to post more than 2 links, I apologize for trying to circumvent the rule but it is relevant)
Any help would be appreciated.
Related
I am trying to develop a GUI based chat-server.I built a client class which has the code to generate the GUI for the client and the methods to write to the server and then to read from the server.The client class writes the message to the buffer of ServerSocket when the send button is clicked.
But the problem is that,after executing more than one client when i write message in the JTextField of a client GUI and then click send then the message gets visible only in the JTextArea of that particular instance of client while JTextArea of other instances of client remain empty i.e no updation takes place in them.
I noticed in the console that JVM puts the instances of the client classes in EventQueue.
I want that updation should take place in every JTextArea of each client's instance.Can somebody help me to achieve this ?
Client Code
import java.io.*;
import java.net.*;
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
class TestClient88 implements ActionListener
{
Socket s;
DataOutputStream dout;DataInputStream din;BufferedReader br;
static String nameOfClient=null;
static String message=null;
JFrame frame;
JTextArea textArea;
JTextField textField;
JButton button;
public TestClient88 ()
{ //just at the time of login
System.out.println("enter ur name");
nameOfClient=new Scanner(System.in).nextLine();
frame=new JFrame(nameOfClient);
textArea=new JTextArea();
textArea.setBounds(0,0,500,400);
textArea.setEditable(false);
textField=new JTextField();
textField.setBounds(0,405,350,30);
// textField.setText("test");
button=new JButton("send");
button.setBounds(355,405,100,30);
// button.addActionListener(this);
button.addActionListener(this);
frame.add(textField);
frame.add(textArea);
frame.add(button);
frame.setSize(500,500);
frame.setLayout(null);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
try{
s=new Socket("localhost",10);
System.out.println(s);
din=new DataInputStream(s.getInputStream());
dout=new DataOutputStream(s.getOutputStream());
br=new BufferedReader(new InputStreamReader(System.in));//to put the name of client in the server socket
}catch(Exception e){}
}
public void actionPerformed(ActionEvent ae)
{
message=textField.getText();
System.out.println("message is "+message);
textField.setText("");
try{
clientchat();
}catch(Exception e){}
}
public void clientchat() throws IOException
{ // //receiving thread to receive message from server
System.out.println("after start "+Thread.currentThread().getName()); //Main thread
String s1=null;
s1=message;
System.out.println("s1 is "+s1);
try{
dout.writeUTF(nameOfClient+" : " +s1);
message=null;
dout.flush();
// Thread.sleep(20000);
String s2=din.readUTF();
System.out.println("message sent from server is "+ s2);
textArea.append(s2+"\n");
}catch(Exception e){}
}
public static void main(String ar[])
{
new TestClient88();
}
}
Server Code
import java.io.*;
import java.net.*;
import java.util.*;
public class Myserver1
{
ArrayList al=new ArrayList();ServerSocket ss;Socket s;
// static ArrayList clientsList=new ArrayList();
static int count;
ObjectInputStream oin;
public Myserver1()
{
try{
ss=new ServerSocket(10);
System.out.println("server socket is "+ss);
while(true)
{
s=ss.accept();//waits for the client socket
System.out.println("client connected");
System.out.println("mike testing");
al.add(s);
Iterator i=al.iterator();
while(i.hasNext())
{
System.out.println("inside while");
System.out.println(i.next());
}
System.out.println("startting server thread ");
Runnable r=new MyThread(s,al);
Thread t=new Thread(r);
t.start();
}
}catch(Exception e){}
}
public static void main(String ar[])
{
new Myserver1();
}
}
class MyThread implements Runnable
{
Socket s;ArrayList al;
MyThread(Socket s,ArrayList al)
{
this.s=s;
this.al=al;
}
public void run()
{
String s1;int i=0;
try{
DataInputStream din=new DataInputStream(s.getInputStream());
do{
s1=din.readUTF();//message of each client
System.out.println(s1);
if(!s1.equals("stop"))
{
tellEveryone(s1);
}
else
{
DataOutputStream dout=new DataOutputStream(s.getOutputStream());
dout.writeUTF(s1);
dout.flush();
al.remove(s);//logging out a client from the server.
}
}while(!s1.equals("stop"));
}catch(Exception e){}
}
public void tellEveryone(String s1)
{
Iterator i=al.iterator();
while(i.hasNext())
{
try{
Socket sc=(Socket)i.next();
DataOutputStream dout=new DataOutputStream(sc.getOutputStream());
dout.writeUTF(s1);
dout.flush();
// System.out.println("client");
}catch(Exception e){}
}
}
}
I am trying to set up a server class, and i'm running into a issue in which no error is being thrown.
import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Server extends JFrame implements Runnable{
private static final long serialVersionUID = 1L;
private JTextField userText;
private JTextArea chatWindow;
private ObjectOutputStream output;
private ObjectInputStream input;
private ServerSocket server;
private Socket connection;
//constructor
public Server(){
super("Server");
userText = new JTextField();
userText.setEditable(false);
userText.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent event){
sendMessage(event.getActionCommand());
userText.setText("");
}
}
);
add(userText, BorderLayout.NORTH);
chatWindow = new JTextArea();
add(new JScrollPane(chatWindow));
setSize(300, 150); //Sets the window size
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public void run(){
try{
server = new ServerSocket(6789, 100); //6789 is a dummy port for testing, this can be changed. The 100 is the maximum people waiting to connect.
while(true){
try{
//Trying to connect and have conversation
waitForConnection();
setupStreams();
whileChatting();
}catch(EOFException eofException){
showMessage("\n Server ended the connection! ");
} finally{
closeConnection(); //Changed the name to something more appropriate
}
}
} catch (IOException ioException){
ioException.printStackTrace();
}
}
//wait for connection, then display connection information
private void waitForConnection() throws IOException{
showMessage(" Waiting for someone to connect... \n");
connection = server.accept();
showMessage(" Now connected to " + connection.getInetAddress().getHostName());
}
//get stream to send and receive data
private void setupStreams() throws IOException{
output = new ObjectOutputStream(connection.getOutputStream());
output.flush();
input = new ObjectInputStream(connection.getInputStream());
showMessage("\n Streams are now setup \n");
}
//during the chat conversation
private void whileChatting() throws IOException{
String message = " You are now connected! ";
sendMessage(message);
ableToType(true);
do{
try{
message = (String) input.readObject();
showMessage("\n" + message);
}catch(ClassNotFoundException classNotFoundException){
showMessage("The user has sent an unknown object!");
}
}while(!message.equals("CLIENT - END"));
}
public void closeConnection(){
showMessage("\n Closing Connections... \n");
ableToType(false);
try{
output.close(); //Closes the output path to the client
input.close(); //Closes the input path to the server, from the client.
connection.close(); //Closes the connection between you can the client
}catch(IOException ioException){
ioException.printStackTrace();
}
}
//Send a mesage to the client
private void sendMessage(String message){
try{
output.writeObject("SERVER - " + message);
output.flush();
showMessage("\nSERVER -" + message);
}catch(IOException ioException){
chatWindow.append("\n ERROR: CANNOT SEND MESSAGE, PLEASE RETRY");
}
}
//update chatWindow
private void showMessage(final String text){
SwingUtilities.invokeLater(
new Runnable(){
public void run(){
chatWindow.append(text);
}
}
);
}
private void ableToType(final boolean tof){
SwingUtilities.invokeLater(
new Runnable(){
public void run(){
userText.setEditable(tof);
}
}
);
}
}
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
public class Menu extends JFrame implements ActionListener{
private static final long serialVersionUID = 1L;
private JButton server;
private JButton client;
private static String Host;
public Menu(){
this.getContentPane().setPreferredSize(new Dimension(300, 300));
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLayout(null);
this.pack();
this.setLocationRelativeTo(null);
server = new JButton();
server.setText("server");
server.setBounds(0, 0, 300, 150);
server.addActionListener(this);
client = new JButton();
client.setText("client");
client.setBounds(0, 150, 300, 150);
client.addActionListener(this);
this.add(server);
this.add(client);
this.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if(e.getSource() == server){
Server s = new Server();
s.run();
}
if(e.getSource() == client){
Host = JOptionPane.showInputDialog("Enter Server I.P.");
Client c = new Client(Host);
c.run();
}
}
public static void main(String[] args){
new Menu();
}
}
The JFrame is created, but can only be exited by the termination button in eclipse, not the default_exit_on_close operation, and is see through (not opaque as it should be). The client class acts the same way, leading me to believe that the issue is the:
Server s = new Server();
s.run();
since if i have the main method call that, everything works fine.
Your constructor can never exit.
This waitForConnection()/setUpStreams() logic is not appropriate. You need an accept loop that just accepts sockets, constructs a Runnable to handle the connection, and starts a thread. That loop should be in a separate run() method and be executed in a separate thread. Not in a constructor.
NB The Socket that is returned by accept() must be a local variable in that loop, otherwise you are liable to run into concurrency problems.
I have implemented a chat client. And as of now it only fully works in cmd, because I can't figure out how I'm supposed to implement the send button in the chat client GUI.
So this is my chat client class:
class ChatClientClass {
private String host;
private int port;
private Socket socket;
private PrintWriter out;
private BufferedReader in;
private BufferedReader stdIn;
ChatWindow chatWindow = new ChatWindow();
public ChatClientClass(String host, int port) {
try {
this.socket = new Socket(host, port);
this.out =
new PrintWriter(socket.getOutputStream(), true);
this.in =
new BufferedReader(
new InputStreamReader(socket.getInputStream()));
this.stdIn =
new BufferedReader(
new InputStreamReader(System.in));
String userInput;
while ((userInput = stdIn.readLine()) != null) {
out.println(userInput);
chatWindow.addText("You: " + userInput);
String serverMessage = in.readLine();
chatWindow.addText(serverMessage);
}
} catch (UnknownHostException e) {
System.err.println("Couldn't not find host " + host);
e.printStackTrace();
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection to " + host);
e.printStackTrace();
System.exit(1);
}
}
}
As of now, I can only write stuff in the command prompt. But what I've written as well as what the server answers will appear in my GUI. The addText(String text)-method adds the input and the output to my GUI.
But I can't figure out how to implement my send button. An easy way would be if I could just send a reference to the PrintWriter and a reference to the GUI when I call the constructor of my ActionListener class, and just do something like: thePrintWriter.println( [get the value of the text area that belongs to the send button] ) in the public void actionPerformed(ActionEvent e)-method. But since I can't/shouldn't call the constructor of my ActionListener from my chat client class, hence sending those references. That wont be possible, right?
I also thought about making the PrintWriter variable static, and also making the JTextArea containing the message I want to send variable static, and then create static methods to access these two variables. But it just feels like I'm doing something terribly wrong when I'm doing that. And I can't get that to work either.
So how is a send button in a chat client supposed to be implemented?
Thanks in advance!
If you are new in GUI building in java/eclipse.
I suggest you the gui builder:
http://www.eclipse.org/windowbuilder/
Its really easy to use, and you can make simple GUI-for your app.
To your problem you will need a button to your frame, and you need to add an actionlistener than if you fire it you can do what you want.
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
public class ButtonAction {
private static void createAndShowGUI() {
JFrame frame1 = new JFrame("JAVA");
frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton button = new JButton(" >> JavaProgrammingForums.com <<");
//Add action listener to button
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
//Execute when button is pressed
//Here call your sender fucntion
out.println(userInput);
chatWindow.addText("You: " + userInput);
String serverMessage = your_jtext.getText();
chatWindow.addText(serverMessage);
System.out.println("You clicked the button");
}
});
frame1.getContentPane().add(button);
frame1.pack();
frame1.setVisible(true);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
I try to build server that could talk with several clients at the same time.
But there are some problems with the thread, and the code doesn't work well.
Could you tell me what is wrong with the thread part? Thank you very much.
public class ServerMulti extends JFrame implements ActionListener{
private static final int PORT = 60534;
private JTextField textField = new JTextField();
private static JTextArea textArea = new JTextArea();
private JButton button = new JButton();
public static ServerSocket server;
public static Socket socket;
public static BufferedReader in;
public static PrintWriter out;
public ServerMulti(){
/*
* build up GUI
*/
setTitle("Server Multi");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300,400);
setBackground(Color.white);
setLayout(new BorderLayout());
button.setText("Send");
button.setSize(300, 50);
textField.setText("Type here");
textArea.setSize(300, 50);
add(textField, BorderLayout.NORTH);
add(new JScrollPane(textArea), BorderLayout.CENTER);
add(button, BorderLayout.SOUTH);
setLocation(300, 100);
button.addActionListener(this);
setVisible(true);
}
/*
* print out the information that need to sent to clients
*
*/
public void actionPerformed(ActionEvent e) {
textArea.append(textField.getText()+"\n");
out.println(textField.getText());
textField.setText("");
}
public static void main(String[] args) throws IOException{
new ServerMulti();
//build up the socket and server
try{
server = new ServerSocket(PORT);
socket = server.accept();
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new PrintWriter(socket.getOutputStream());
textArea.append("Connected. "+" Port: " + PORT + "\n");
while(true){
worker w = new worker();
Thread t = new Thread(w);
t.start();
}
}catch (IOException e) {
System.out.println("Accept failed:" +PORT);
System.exit(-1);
}
}
//to the same server, different sockets are created connecting to different client
public static class worker implements Runnable{
public void run() {
String msg;
/*
* the "in.readLine()" give the data only once
* 1. so we save the information to a String from the socket
* 2. Then sent out a feedback to client, through socket
* 3. print out the String we just collected
*/
while(true){
try {
msg = in.readLine();
out.println("Server received : " + msg);
textArea.append(msg+"\n");
} catch (IOException e) {
System.out.println("Fail");
e.printStackTrace();
}
}
}
}
}
There are a couple of problems with this, but in terms of multithreading the server: ServerSocket.accept() blocks until a new client attempts to connect. In your code this only happens once; so only one client will be accepted. The layout should instead be something like this:
ServerSocket ss = new ServerSocket(PORT);
while (LISTENING) {
Socket sock = ss.accept();
Handler handler = new Handler(sock);
new Thread(handler).start();
//With the LISTENING variable dealt with as well
}
Here the class Handler should be a Runnable class that deals with the socket on another thread. The while loop can then go back and accept a new connection.
i'm trying to create a server that allows several clients, I can connect with one client fine, but I cant with two. The was I try to connect two clients to the server is by creating two client objects and one server in a main method. Here is the code for the Server:
public class DraughtsSever extends JFrame{
JPanel panel;
JTextArea gamesList;
ServerSocket draughtsSS;
JScrollPane scroll;
Socket s;
int i = 0;
DraughtsSever(){
panel = new JPanel();
panel.setPreferredSize(new Dimension(350,350));
gamesList = new JTextArea();
//scroll.setPreferredSize(new Dimension(350,350));
gamesList.setPreferredSize(new Dimension(300,300));
//scroll.add(GamesList);
//scroll = new JScrollPane(GamesList, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
//panel.add(scroll);
this.add(panel);
panel.add(gamesList);
this.setSize(400,400);
this.setVisible(true);
this.setTitle("Draughts Server");
panel.add(gamesList);
allowConnections();
}
public void allowConnections(){
gamesList.append("Server listening on port 50000...");
try{
while(true){
draughtsSS = new ServerSocket(50000);
//s = draughtsSS.accept();
new Thread(new TestT(draughtsSS.accept())).start();
//t.start();
}
}
catch(IOException e){
System.out.println("Error :"+e.getMessage());
}
}
class TestT implements Runnable{
Socket s;
TestT(Socket s){
this.s = s;
}
public void run(){
try{
PrintWriter out = new PrintWriter(s.getOutputStream());
Scanner in = new Scanner(s.getInputStream());
gamesList.append("\n"+s.getInetAddress().toString() +" has connected.");
JOptionPane.showMessageDialog(new JFrame(), "Successfully connected");
out.println("hello");
System.out.println(s.getInetAddress().toString() +" has connected.");
}
catch(IOException e){
}
}
}
}
Here is the method in the client that I use to connect to the server
private void setupConnection(String serverIP, String port){
int portInt = Integer.parseInt(port);
try{
InetAddress IP = InetAddress.getByName(serverIP);
int intPort = Integer.parseInt(port);
Socket clientSocket = new Socket(IP,intPort);
JOptionPane.showMessageDialog(new JFrame(), "Successfully connected to Server");
PrintWriter out = new PrintWriter(clientSocket.getOutputStream());
Scanner in = new Scanner(clientSocket.getInputStream());
//in.
}
catch(Exception e){
System.out.println("ErrorC :" +e.getMessage());
}
}
}
}
I think you should only create the server socket once, so move this outside of the while loop:
draughtsSS = new ServerSocket(50000);
You don't need to keep re-creating this because when clients connect they automatically get moved to a different socket when you call
draughtsSS.accept()