Im building a simple chat client which is only supposed to be able to send and receive messages.
Im using a server running on my own computer that sends back whatever message is sent to it, to all the user that's connected to the server.
When I send messages to the server by clicking my "send button", the server isn't sending back the message to me as it's supposed to. So either my output stream isn't working, or my listener for input messages isn't working but can't figure out what is wrong.
I might add, that i don't get any error messages/exceptions and connecting to the server works
public class Chatt extends JFrame implements Runnable{
private JPanel topPanel = new JPanel();
private JPanel bottomPanel = new JPanel();
private JTextArea chattArea = new JTextArea();
private JButton sendButton = new JButton("Skicka");
private JLabel chattPerson = new JLabel("Du chattar med: ");
private JTextField chattField = new JTextField(15);
private Thread thread;
private int port;
private String ip;
private DataInputStream in;
private DataOutputStream out;
private Socket s;
public Chatt(String ip, int port){
this.ip=ip;
this.port=port;
Konstruktor();
}
public Chatt(){
ip="127.0.0.1";
port=2000;
Konstruktor();
}
public Chatt(String ip){
this.ip=ip;
port=2000;
Konstruktor();
}
public void Konstruktor(){
setLayout(new BorderLayout());
chattArea.setSize(70, 50);
add(chattArea, BorderLayout.CENTER);
bottomPanel.setLayout(new BoxLayout(bottomPanel, BoxLayout.X_AXIS));
bottomPanel.add(sendButton);
bottomPanel.add(chattField);
sendButton.addActionListener(new sendListener());
add(bottomPanel, BorderLayout.SOUTH);
topPanel.setLayout(new BoxLayout(topPanel, BoxLayout.X_AXIS));
topPanel.add(chattPerson);
add(topPanel, BorderLayout.NORTH);
try {
//s = new Socket("atlas.dsv.su.se", 9494);
s=new Socket(ip, port);
}
catch (UnknownHostException e) {
System.out.println("Connection failed");
}
catch (IOException e) {
}
try{
in= new DataInputStream(new BufferedInputStream(s.getInputStream()));
out= new DataOutputStream(new BufferedOutputStream(s.getOutputStream()));
}
catch(UnknownHostException e){
System.out.println("Host unknown");
}
catch(IOException e){
}
thread = new Thread(this);
thread.start();
setTitle("Connected to "+ip+" på port "+port);
chattArea.setEditable(false);
setSize(400, 500);
setVisible(true);
setResizable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public void run() {
while(true){
System.out.println("tråden igång");
try {
String temp = in.readUTF();
System.out.println(temp);
chattArea.append(temp);
} catch (IOException e) {
}
}
}
public class sendListener implements ActionListener{
public void actionPerformed(ActionEvent e){
String chattString = chattField.getText();
try {
out.writeUTF(chattString);
out.flush();
}
catch (IOException e1) {
}
chattArea.append("Du: "+chattString+"\n");
chattField.setText("");
}
}
public static void main(String[] args){
//new Chatt("127.0.0.1", 2000);
//new Chatt();
new Chatt("127.0.0.1");
}
}
I can confirm that the chatserver wasn't working correctly. I did build my own server and sending/reciving messages works fine, so nothing wrong with my code.
Related
I was writing a TCP chat program.
Here is my output.
As you can see only first message from each peer is reaching the other end.
Second message on wards are not displayed.
Here is my full code. You can run it. Where am I wrong?
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import java.net.*;
import javax.swing.*;
class chattcp extends JFrame {
public static void main(String args[]){
chattcp peer1=new chattcp("peer1",9999,9998);
chattcp peer2=new chattcp("peer2",9998,9999);
}
chattcp(String name,int lis,int snd){
this.setVisible(true);
this.setTitle(name);
this.setLayout(null);
this.setSize(500,500);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
TextField tf=new TextField();
this.add(tf);
tf.setBounds(10,20,100,40);
TextArea ta=new TextArea();
this.add(ta);
ta.setBounds(10,80,400,400);
ta.setEditable(false);
ta.setFont(ta.getFont().deriveFont(20f));
Button b=new Button("send");
this.add(b);
b.setBounds(130,20,60,40);
b.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent a){
try{
String s= tf.getText();
Socket skt=new Socket("localhost",snd);
DataOutputStream dos= new DataOutputStream(skt.getOutputStream());
dos.writeUTF(s);
ta.append("You :"+s+"\n");
tf.setText("");
}
catch(IOException e){
e.printStackTrace();
}
}
});
Thread receive=new Thread() {
public void run(){
try{
ServerSocket ser=new ServerSocket(lis);
Socket sktt=ser.accept();
DataInputStream dis= new DataInputStream(sktt.getInputStream());
while (true){
String s= dis.readUTF();
ta.append("Friend : "+s+"\n");
}
}catch(IOException e){e.printStackTrace();}
}
};
receive.start();
}
}
Everytime you click your send button you create a new socket and try to connect.
The problem is, once you send something, the socket is created, the serversocket accepts and starts the loop.
When you now write the second message, you are creating a new socket while the loop is still trying to read from the OutputStream from the old socket.
one solution to your problem is to close the serversocket after each read and create a new serversocket each iteration:
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import java.net.*;
import javax.swing.*;
public class chattcp extends JFrame {
public static void main(String args[]) {
chattcp peer1 = new chattcp("peer1", 9999, 9998);
chattcp peer2 = new chattcp("peer2", 9998, 9999);
}
chattcp(String name, int lis, int snd) {
this.setVisible(true);
this.setTitle(name);
this.setLayout(null);
this.setSize(500, 500);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
TextField tf = new TextField();
this.add(tf);
tf.setBounds(10, 20, 100, 40);
TextArea ta = new TextArea();
this.add(ta);
ta.setBounds(10, 80, 400, 400);
ta.setEditable(false);
ta.setFont(ta.getFont().deriveFont(20f));
Button b = new Button("send");
this.add(b);
b.setBounds(130, 20, 60, 40);
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent a) {
try {
String s = tf.getText();
Socket skt = new Socket("localhost", snd);
DataOutputStream dos = new DataOutputStream(skt.getOutputStream());
dos.writeUTF(s);
ta.append("You :" + s + "\n");
tf.setText("");
} catch (IOException e) {
e.printStackTrace();
}
}
});
Thread receive = new Thread() {
public void run() {
try {
while (true) {
ServerSocket ser = new ServerSocket(lis);
Socket sktt = ser.accept();
DataInputStream dis = new DataInputStream(sktt.getInputStream());
String s = dis.readUTF();
ta.append("Friend : " + s + "\n");
ser.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
};
receive.start();
}
}
a better solution would be to not always create a new socket, when you send something, but i am lazy and this solution is easier to edit your code to, so i just used it.
You are creating a new connection every time that you click on the send button, but the Server only listen one time.
One simple answer is to save the Socket e reuse it.
class chattcp extends JFrame {
public static void main(String args[]){
chattcp peer1=new chattcp("peer1",9999,9998);
chattcp peer2=new chattcp("peer2",9998,9999);
}
Socket skt = null;
chattcp(String name,int lis,int snd){
this.setVisible(true);
this.setTitle(name);
this.setLayout(null);
this.setSize(500,500);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
TextField tf=new TextField();
this.add(tf);
tf.setBounds(10,20,100,40);
TextArea ta=new TextArea();
this.add(ta);
ta.setBounds(10,80,400,400);
ta.setEditable(false);
ta.setFont(ta.getFont().deriveFont(20f));
Button b=new Button("send");
this.add(b);
b.setBounds(130,20,60,40);
b.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent a){
try{
if (skt == null) {
skt = new Socket("localhost",snd);
}
DataOutputStream dos= new DataOutputStream(skt.getOutputStream());
String s= tf.getText();
dos.writeUTF(s);
ta.append("You :"+s+"\n");
tf.setText("");
}
catch(IOException e){
e.printStackTrace();
}
}
});
Thread receive=new Thread() {
public void run(){
try{
ServerSocket ser=new ServerSocket(lis);
Socket sktt=ser.accept();
DataInputStream dis= new DataInputStream(sktt.getInputStream());
while (true){
String s= dis.readUTF();
ta.append("Friend : "+s+"\n");
}
}catch(IOException e){e.printStackTrace();}
}
};
receive.start();
}
}
im trying to run client-server program with my friend. it basic chat.
but even i gave him my ip number it dont manage to connect to start.
we use system.out. println and the client server failed all the after
waitnig 1 min and print the "didnt manage to connect".
please advice.
public class MyPanel extends JPanel{
private JButton btnSend;
private JTextArea txt;
ServerSocket serverSocket = null;
**Server SIDE:**
public MyPanel()
{
this.setLayout(new BorderLayout());
this.add(getBtn() , BorderLayout.SOUTH);
this.add(getText() , BorderLayout.CENTER);
try{
System.out.println("here");
serverSocket = new ServerSocket(6600);
System.out.println("Server's ready");
Socket clientSocket = serverSocket.accept();
System.out.println("after accept");
PrintWriter out = new PrintWriter(clientSocket.getOutputStream() , true);
out.flush();
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String temp;
while( (temp = in.readLine())!= null)
out.println(temp);
}catch(IOException e){}
}
public JButton getBtn(){
btnSend = new JButton("send");
btnSend.addActionListener(new MyAction());
return btnSend;
}
public JTextArea getText(){
txt = new JTextArea();
return txt;
}
private class MyAction implements ActionListener{
public void actionPerformed(ActionEvent e) {
}
Client SIDE
public class Messages extends JPanel{
private JTextArea txtArea;
private JButton sendBtn;
private Socket socket;
private InetAddress address;
private PrintWriter out;
private BufferedReader in;
public Messages(){
this.setLayout(new BorderLayout());
txtArea = new JTextArea();
add(txtArea, BorderLayout.CENTER);
sendBtn = new JButton("Send");
add(sendBtn, BorderLayout.SOUTH);
addClient();
}
public void addClient(){
try{
//address = InetAddress.getByName("");
//System.out.println(address);
socket = new Socket("**here we type my ip numbeer as string", 6600);
}catch(IOException e){
System.out.println("Didn't manage to connect");
}
try{
out = new PrintWriter(socket.getOutputStream(),true);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
}catch(IOException e){
System.out.println("Buffer problem");
}
System.out.println("Connected");
}
}
Ping the server machine IP & check whether its reachable. If ping works then check the firewall running in the server machine for any rule which blocks the communication.
So my chat server that im making only connects to clients on port 5000. I can only broadcast info out to everyone at the same time.
Is there any way to send a message out to one person? Like a Server Message of the day (or is the way I coded it totally wrong and I have to do a major overhaul, if so could you please list out what I need to fix?)
This is my server Code:
public class ServerProgram
{
JTextArea incoming;
ArrayList clientOutputStreams;
JTextField outgoing;
public class ClientHandler implements Runnable {
BufferedReader reader;
Socket sock;
public ClientHandler(Socket clientSocket){
try{
sock = clientSocket;
InputStreamReader isReader = new InputStreamReader(sock.getInputStream());
reader = new BufferedReader(isReader);
} catch(Exception e) {e.printStackTrace();}
}
public void run(){
String message;
try{
while ((message=reader.readLine())!=null){
incoming.append("USER: "+message+"\n");
tellEveryone(message);
}
}catch(Exception e){e.printStackTrace();}
}
}
public static void main (String[] args){
new ServerProgram().go();
}
public void go(){
clientOutputStreams = new ArrayList();
JFrame frame = new JFrame("Simple Chat Server");
JPanel mainPanel = new JPanel();
incoming = new JTextArea(15,50);
incoming.setLineWrap(true);
incoming.setWrapStyleWord(true);
incoming.setEditable(false);
JScrollPane qScroller = new JScrollPane(incoming);
qScroller.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
qScroller.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
outgoing = new JTextField(20);
JButton sendButton = new JButton ("Send");
sendButton.addActionListener(new SendButtonListener());
mainPanel.add(qScroller);
mainPanel.add(outgoing);
mainPanel.add(sendButton);
frame.getContentPane().add(BorderLayout.CENTER, mainPanel);
frame.setSize(600,500);
frame.setVisible(true);
try{
ServerSocket serverSock = new ServerSocket(5000);
while(true){
Socket clientSocket = serverSock.accept();
PrintWriter writer = new PrintWriter(clientSocket.getOutputStream());
clientOutputStreams.add(writer);
Thread t = new Thread(new ClientHandler(clientSocket));
t.start();
incoming.append("got a connection at "+" \n");}
}catch (Exception e){e.printStackTrace();}
}
public void tellEveryone(String message){
Iterator it = clientOutputStreams.iterator();
while(it.hasNext()){
try{
PrintWriter writer = (PrintWriter) it.next();
writer.println(message);
writer.flush();
}catch(Exception e){e.printStackTrace();}
}
}
private class SendButtonListener implements ActionListener{
public void actionPerformed(ActionEvent ev){
Iterator it = clientOutputStreams.iterator();
if(it.hasNext()==false){
incoming.append(outgoing.getText());
}
else{tellEveryone("!SERVER;!"+outgoing.getText());
incoming.append(outgoing.getText()+"\n");}
outgoing.setText("");
outgoing.requestFocus();
}
}
}
This is my client code:
public class ChatClient
{
JTextArea incoming;
JTextField outgoing;
BufferedReader reader;
PrintWriter writer;
Socket sock;
String UserName;
String ipAdd="127.0.0.1";
int FinishedNet=0;
JMenuBar menuBar;
JMenu menu, submenu;
JMenuItem menuItem;
JRadioButtonMenuItem rbMenuItem;
JCheckBoxMenuItem cbMenuItem;
public static void main(String[] args) throws Exception
{ChatClient chat = new ChatClient();
chat.go();}
public void go(){
menuBar = new JMenuBar();
JFrame frame = new JFrame("Simple Chat client");
JPanel mainPanel = new JPanel();
menu = new JMenu("Menu");
menu.getAccessibleContext().setAccessibleDescription(
"The only menu in this program that has menu items");
menuBar.add(menu);
cbMenuItem = new JCheckBoxMenuItem("Message AutoScroll");
cbMenuItem.addActionListener(new autoScrollListener());
menu.add(cbMenuItem);
frame.setJMenuBar(menuBar);
incoming = new JTextArea(15,50);
incoming.setLineWrap(true);
incoming.setWrapStyleWord(true);
incoming.setEditable(false);
JScrollPane qScroller = new JScrollPane(incoming);
qScroller.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
qScroller.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
outgoing = new JTextField(20);
outgoing.addKeyListener(new EnterListener());
JButton sendButton = new JButton ("Send");
sendButton.addActionListener(new SendButtonListener());
mainPanel.add(qScroller);
mainPanel.add(outgoing);
mainPanel.add(sendButton);
setUpNetworking();
Thread readerThread = new Thread(new IncomingReader());
readerThread.start();
frame.getContentPane().add(BorderLayout.CENTER, mainPanel);
frame.setSize(600,500);
frame.setVisible(true);
incoming.setText("Type /Help to get the help Text \n");
}
private void setUpNetworking(){
try{
ipAdd = JOptionPane.showInputDialog("What is the IP you wish to connect to");
UserName = JOptionPane.showInputDialog("What is your UserName?");
sock = new Socket(ipAdd, 5000);
InputStreamReader streamReader = new InputStreamReader(sock.getInputStream());
reader = new BufferedReader(streamReader);
writer = new PrintWriter(sock.getOutputStream());
incoming.append("Networking Finished");
} catch(IOException e){
e.printStackTrace();}
}
public void SendMessage(String message){
writer.println(UserName+": "+message);
writer.flush();
outgoing.setText("");
outgoing.requestFocus();
}
public void SendMessage(){
try{
incoming.setForeground(Color.RED);
String outText=outgoing.getText();
if(outText.length()>1 && outText.substring(0, 1).equals("/")){
String realOutText=outgoing.getText().substring(1);
if(realOutText.equals("help")){
incoming.append("\n help: Displays the help text \n reconnect: reconnects to any IP \n newUserName: Select a new username \n about: Displays the about text \n ipAddress: Displays your public IP Address to only you \n ipAdressAll: Sends your public IP Adress to everyone on the server \n");
}
else if(realOutText.equals("about")){
incoming.append("\n Coded by Dan Janes with the help of Ian Sacco \n Started on 5/27/2014 \n");
}
else if(realOutText.equals("newUserName")){
String old=UserName;
UserName = JOptionPane.showInputDialog("What is your NEW UserName?");
writer.println(old+" is now known as "+UserName);
writer.flush();
}
else if (realOutText.equals("reconnect")){
setUpNetworking();
}
else if (realOutText.equals("ipAddress")){
try{ URL whatismyip = new URL("http://bot.whatismyipaddress.com");
BufferedReader in = new BufferedReader(new InputStreamReader(
whatismyip.openStream()));
String ip = in.readLine();
incoming.append("Your IP address is "+ip+"\n");}
catch(Exception e){e.printStackTrace();
}
}
else if (realOutText.equals("ipAddressAll")){
try{URL whatismyip = new URL("http://bot.whatismyipaddress.com");
BufferedReader in = new BufferedReader(new InputStreamReader(
whatismyip.openStream()));
String ip = in.readLine();
SendMessage( UserName+"'s IP address is "+ip);}
catch(Exception e){e.printStackTrace();
}
}
else{
incoming.append("Sorry that is not a command, try /help \n");
}
}
else{
writer.println(UserName+": "+outText);
writer.flush();
}}catch(Exception e) {e.printStackTrace();}
outgoing.setText("");
outgoing.requestFocus();
}
private class SendButtonListener implements ActionListener{
public void actionPerformed(ActionEvent ev){
SendMessage();
}
}
private class autoScrollListener implements ActionListener{
public void actionPerformed(ActionEvent ev){
if(cbMenuItem.isSelected()==true){
incoming.setCaretPosition(incoming.getDocument().getLength());}
}
}
private class EnterListener implements KeyListener{
#Override
public void keyPressed(KeyEvent arg0) {
if(arg0.getKeyCode()==10){
SendMessage();
}
}
#Override
public void keyReleased(KeyEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void keyTyped(KeyEvent arg0) {
// TODO Auto-generated method stub
}
}
public class IncomingReader implements Runnable{
public void run(){
String message;
try{
while ((message=reader.readLine())!=null){System.out.println("read "+message);
incoming.append(message+"\n");
if(cbMenuItem.isSelected()==true){
incoming.setCaretPosition(incoming.getDocument().getLength());}
}
}catch(Exception e){e.printStackTrace();}
}
}
}
I've been working on building a chat server to learn about threading and using sockets. I used head first java as a guide (and I'm still confused about a couple of things, which is why I have this question probably :D) and the code below is what I have.
If you read my code, you'll see that I have clients connect to the server by clicking on a "connect" button. When they do that, a new jframe pops up that asks for their preferred name for the chat session. When they input that, it's saved in a String in the client code. My question is, how do I get this name over to the server, and make it so that every time the client sends a message, their name is displayed before their message?
Thank you for the help!!!
(ALSO, if anyone knows a good link that can explain sockets and how socket/client interaction occurs through threads, that would be great!)
server code:
import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
public class GameServerOne {
ArrayList clientOutputStreams;
String clientName;
private class ClientThreadHandler implements Runnable {
BufferedReader clientIncomingReader;
Socket socket1;
public ClientThreadHandler(Socket clientSocket2) {
try {
socket1 = clientSocket2;
InputStreamReader clientInputReader = new InputStreamReader(socket1.getInputStream());
clientIncomingReader = new BufferedReader(clientInputReader);
} catch (Exception e) {
e.printStackTrace();
}
}
public void run() {
String message;
try {
while ((message = clientIncomingReader.readLine()) != null) {
tellEveryone(message);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
public void tellEveryone(String message) {
Iterator it = clientOutputStreams.iterator();
while(it.hasNext()) {
try {
PrintWriter writer = (PrintWriter) it.next();
writer.println(message);
writer.flush();
} catch (Exception e) {
e.printStackTrace();
}
}
}
public void setUpServer() {
clientOutputStreams = new ArrayList();
try {
ServerSocket gameSocket = new ServerSocket(5151);
//System.out.println("Server Connected");
while (true) {
Socket clientSocket = gameSocket.accept();
PrintWriter writer = new PrintWriter(clientSocket.getOutputStream());
writer.println("User connected");
writer.flush();
clientOutputStreams.add(writer);
Thread t = new Thread(new ClientThreadHandler(clientSocket));
t.start();
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
public static void main(String[] args) {
new GameServerOne().setUpServer();
}
}
Client code:
import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class GameClientOne {
Socket gameSocket;
JFrame inputNameFrame;
JFrame clientFrame;
JTextArea chatArea;
JTextField messageInput;
BufferedReader gameChatReader;
PrintWriter gameChatWriter;
JTextField nameField;
boolean sessionNamePicked = false;
String userSessionName;
BufferedReader gameBufferedReader;
public GameClientOne () {
setUpGUI();
}
public void setUpGUI() {
clientFrame = new JFrame("Game Window");
JPanel mainPanel = new JPanel(new BorderLayout());
JPanel southPanel = new JPanel(new BorderLayout());
JPanel centerPanel = new JPanel(new BorderLayout());
chatArea = new JTextArea();
chatArea.setWrapStyleWord(true);
chatArea.setLineWrap(true);
chatArea.setEditable(false);
JScrollPane chatScroller = new JScrollPane(chatArea);
messageInput = new JTextField();
messageInput.addKeyListener(new MessageInputFieldListener());
JButton sendButton = new JButton("Send");
sendButton.addActionListener(new SendButtonListener());
JPanel westPanel = new JPanel(/*new GridLayout(20, 1)*/);
JPanel eastPanel = new JPanel();
JButton connectButton = new JButton("Connect");
connectButton.addActionListener(new ConnectButtonListener());
connectButton.setPreferredSize(new Dimension(100, 28));
JPanel northPanel = new JPanel(new FlowLayout());
JLabel northTitleLabel = new JLabel("Game Screen");
westPanel.add(connectButton);
chatScroller.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS) ;
chatScroller.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
northPanel.add(northTitleLabel);
centerPanel.add(BorderLayout.CENTER, chatScroller);
southPanel.add(BorderLayout.CENTER, messageInput);
southPanel.add(BorderLayout.EAST, sendButton);
mainPanel.add(BorderLayout.SOUTH, southPanel);
mainPanel.add(BorderLayout.CENTER, centerPanel);
mainPanel.add(BorderLayout.WEST, westPanel);
mainPanel.add(BorderLayout.EAST, eastPanel);
mainPanel.add(BorderLayout.NORTH, northPanel);
clientFrame.add(mainPanel);
clientFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
clientFrame.setSize(450, 600);
clientFrame.setVisible(true);
messageInput.requestFocusInWindow();
}
public void setUpInputNameFrame() {
inputNameFrame = new JFrame("Insert Name");
JPanel mainPanel = new JPanel(new BorderLayout());
nameField = new JTextField();
nameField.addKeyListener(new NameFieldListener());
JButton submitButton = new JButton("Submit");
submitButton.addActionListener(new SubmitButtonListener());
JLabel inputNameLabel = new JLabel("Please pick a name for the chat session");
JPanel northPanel = new JPanel(new FlowLayout());
JPanel southPanel = new JPanel(new BorderLayout());
northPanel.add(inputNameLabel);
southPanel.add(BorderLayout.CENTER, nameField);
southPanel.add(BorderLayout.EAST, submitButton);
mainPanel.add(BorderLayout.NORTH, northPanel);
mainPanel.add(BorderLayout.SOUTH, southPanel);
inputNameFrame.add(mainPanel);
inputNameFrame.setSize(300, 150);
inputNameFrame.setVisible(true);
nameField.requestFocusInWindow();
}
public void connectToGameServer() {
try {
gameSocket = new Socket("127.0.0.1", 5151);
InputStreamReader gameSocketReader = new InputStreamReader(gameSocket.getInputStream());
gameBufferedReader = new BufferedReader(gameSocketReader);
gameChatWriter = new PrintWriter(gameSocket.getOutputStream());
chatArea.append("Connected with name: " + userSessionName + "\n");
Thread incomingTextThread = new Thread(new IncomingTextReader());
incomingTextThread.start();
//System.out.println("Connected to Game");
} catch (Exception e) {
System.out.println("Could not connect to game...");
e.printStackTrace();
}
}
//ALL LISTENER CLASSES BELOW HERE
//main chat page listeners
private class ConnectButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
if (!sessionNamePicked) {
setUpInputNameFrame();
} else {
chatArea.append("You already connected!\n");
}
}
}
private class SendButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
if (!sessionNamePicked) {
chatArea.append("Please connect first\n");
messageInput.setText("");
messageInput.requestFocusInWindow();
} else {
try {
gameChatWriter.println(messageInput.getText());
gameChatWriter.flush();
} catch (Exception ex2) {
ex2.printStackTrace();
}
//chatArea.append(userSessionName + ": " + messageInput.getText() + "\n");
messageInput.setText("");
messageInput.requestFocusInWindow();
}
}
}
private class MessageInputFieldListener implements KeyListener {
public void keyPressed(KeyEvent e) {
}
public void keyTyped(KeyEvent e) {
}
public void keyReleased(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_ENTER) {
if (!sessionNamePicked) {
chatArea.append("Please connect first\n");
messageInput.setText("");
} else {
try {
gameChatWriter.println(messageInput.getText());
gameChatWriter.flush();
} catch (Exception ex2) {
ex2.printStackTrace();
}
//chatArea.append(userSessionName + ": " + messageInput.getText() + "\n");
messageInput.setText("");
}
}
}
}
//pick chat session name listeners: nameField/submitButton
private class NameFieldListener implements KeyListener {
public void keyPressed(KeyEvent e) {
}
public void keyTyped(KeyEvent e) {
}
public void keyReleased(KeyEvent e) {
if (!nameField.getText().isEmpty() && e.getKeyCode() == KeyEvent.VK_ENTER) {
userSessionName = nameField.getText();
sessionNamePicked = true;
connectToGameServer();
inputNameFrame.dispose();
messageInput.requestFocusInWindow();
}
}
}
private class SubmitButtonListener implements ActionListener {
public void actionPerformed (ActionEvent e) {
if (!nameField.getText().isEmpty()) {
userSessionName = nameField.getText();
sessionNamePicked = true;
connectToGameServer();
inputNameFrame.dispose();
messageInput.requestFocusInWindow();
}
}
}
//Runnable implementation for threads
private class IncomingTextReader implements Runnable {
public void run() {
String incomingMessage;
try {
while ((incomingMessage = gameBufferedReader.readLine()) != null) {
chatArea.append(incomingMessage + "\n");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
GameClientOne gameClient = new GameClientOne();
}
}
If you want to send more than just a message as you are now, you are going to need a protocol to decide what to do with the string you receive, instead of just sending it to all the other clients.
For example, on the client side to send the client's name you might write NAME:(client's name), and then on the server you would split the string at the : and check if the first part is NAME, and if so set the clients name to the rest of the string. You should think about what other types of data you might want to send aswell and design a protocol that works for it.
Here's an example of how to do the above:
On the client you could add the line gameChatWriter.write("NAME:"+name) (create name first of course) imediatly after the connection is made. Then on the server, instead of calling tellEveryone(message) when the message is recieved create a method called processInput and call it, which might look like this:
private void processInput(String message){
String[] commands=message.split(':');
if(commands[0].equals("NAME")){
clientName=commands[1];
}
else{
tellEveryone(message);
}
}
Right now you only have one String clientName and you will obviously need more for the other clients you want to talk to so I would recommend making the thread handler into a seperate class which you would instantiate for each client and could hold things like that.
After you get this to work you could also create a seperate method to write other things that you want to send to either the client or server and a method to process input on the client side as well. Hope this helps.
Hi I've been working on a Server/Client Chat Program in which I need a GUI for the client . I've got the basic console Client/Server communicating correctly but I can't get the input/output of the client to display on the Client GUI can somebody please take a look and give me suggestions on as to how I can get the output of the Client to work on the ClientGUI using the text field as input and then broadcasting it to the text area? I've placed my code below.
DATA OBJECT
import java.io.*;
import java.net.*;
public class DataObject implements Serializable{
String message;
public DataObject(){}
public DataObject(String message){
setMessage(message);
}
public void setMessage(String message){
this.message = message;
}
public String getMessage(){
return message;
}
}
ThreadedChatServer
import java.io.*;
import java.net.*;
import java.util.*;
public class ThreadedChatServer{
ThreadedChatClient tcg;
int port;
public ThreadedChatServer(int port){
this.port=port;
try{
ArrayList<ThreadedChatHandler> handlers = new ArrayList<ThreadedChatHandler>();
ServerSocket ss = new ServerSocket(port);
for(;;){
System.out.println("Waiting for clients on port " +port+"...");
System.out.println("If running client from console type 'java ThreadedChatClient [String Username] [String host] [int Port]'");
Socket s = ss.accept();
System.out.println("New user has entered.");
new ThreadedChatHandler(s, handlers).start();
}
}catch(Exception e){
System.out.println(e.getMessage());
}
}
public static void main(String[] args){
ThreadedChatServer tcs= new ThreadedChatServer(1999);
}
}
class ThreadedChatHandler extends Thread{
ThreadedChatClient tcg;
public ThreadedChatHandler(Socket s, ArrayList<ThreadedChatHandler> list){
this.s = s;
this.list = list;
this.list.add(this);
}
public synchronized void broadcast(DataObject d) throws IOException{
for(ThreadedChatHandler handler: list){
handler.oos.writeObject(d);
}
}
public void run(){
try{
ois = new ObjectInputStream(s.getInputStream());
oos = new ObjectOutputStream(s.getOutputStream());
objIn= new DataObject( "User has entered.");
broadcast(objIn);
while(true){
obj = (DataObject)ois.readObject();
broadcast(obj);
}
}catch(Exception e){
System.out.println(e.getMessage());
}finally{
try{
objOut= new DataObject("User has left.");
broadcast(objOut);
list.remove(this);
ois.close();
oos.close();
s.close();
}catch(IOException ioe){
System.out.println(ioe.getMessage());
}
}
}
DataObject obj,objIn,objOut;
Socket s;
ArrayList<ThreadedChatHandler> list;
ObjectInputStream ois;
ObjectOutputStream oos;
}
ThreadedChatClient
DataObject in, out;
ObjectOutputStream oos;
ObjectInputStream ois;
Scanner scan;
String username;
ChatClientGUI cg;
public ThreadedChatClient(String username,String host,int port){
this.username=username;
scan = new Scanner(System.in);
try{
s = new Socket(host,port);
oos = new ObjectOutputStream(s.getOutputStream());
}catch(Exception e){
System.out.println(e.getMessage());
}
this.start();
for(;;){
String temp = scan.nextLine();
out = new DataObject(temp);
try{
out.setMessage(username+": "+out.getMessage());
oos.writeObject(out);
}catch(Exception e){
System.out.println(e.getMessage());
}
}
}
public void run(){
try{
ois = new ObjectInputStream(s.getInputStream());
}catch(Exception e){
System.out.println(e.getMessage());
}
for(;;){
try{
in = (DataObject)ois.readObject();
}catch(Exception e){
System.out.println(e.getMessage());
}
System.out.println(in.getMessage());
}
}
public static void main(String[] args){
ThreadedChatClient c = new ThreadedChatClient(args[0],args[1],Integer.parseInt(args[2]));
}
}
ChatClientGUI
import java.awt.*;
import java.awt.event.*;
public class ChatClientGUI extends Frame implements ActionListener{
Canvas c;
TextField tfServer,tfPort,tfUsername,tf;
TextArea ta;
int defaultPort;
String defaultHost,defaultUsername;
Label label;
Button b,b2;
List lst;
ThreadedChatClient cc;
int finalY,finalX;
public ChatClientGUI(String username,String host,int port){
super("ChatClientGUI");
defaultPort = port;
defaultHost = host;
defaultUsername= username;
setSize(600,600);
addWindowListener(new WindowAdapter (){
public void windowClosing(WindowEvent we){
System.exit(0);
}
});
Panel nPanel = new Panel(new GridLayout(3,1));
Panel serverAndPort = new Panel(new GridLayout());
tfServer = new TextField(host);
tfServer.addActionListener(this);
tfPort = new TextField("" + port);
tfPort.addActionListener(this);
tfUsername= new TextField(defaultUsername);
tfUsername.addActionListener(this);
serverAndPort.add(new Label("Username:"));
serverAndPort.add(tfUsername);
serverAndPort.add(new Label("Server Address: "));
serverAndPort.add(tfServer);
serverAndPort.add(new Label("Port Number: "));
serverAndPort.add(tfPort);
nPanel.add(serverAndPort);
label = new Label("Enter your message below");
nPanel.add(label);
tf = new TextField();
tf.setBackground(Color.WHITE);
nPanel.add(tf);
add(nPanel, BorderLayout.NORTH);
////
Panel cPanel= new Panel(new GridLayout(2,1));
ta= new TextArea();
cPanel.add(ta);
ta.setEditable(false);
c=new Canvas();
c.setBackground(Color.BLACK);
c.setForeground(Color.WHITE);
c.setEnabled(true);
cPanel.add(c);
add(cPanel,BorderLayout.CENTER);
//////
Panel sPanel= new Panel(new GridLayout());
Panel inOutPanel= new Panel(new GridLayout());
b= new Button("Login");
b.addActionListener(this);
b.setBackground(Color.GREEN);
inOutPanel.add(b);
b2= new Button("Logout");
b2.addActionListener(this);
b2.setBackground(Color.RED);
b2.setEnabled(false);
inOutPanel.add(b2);
lst = new List(4,false);
lst.add("*List Of Users*");
inOutPanel.add(lst);
sPanel.add(inOutPanel);
add(sPanel,BorderLayout.SOUTH);
}
public void actionPerformed(ActionEvent e) {
Object o= e.getSource();
if(o==b){
int por=0;
por = Integer.parseInt(tfPort.getText());
ta.append(tfUsername.getText()+" has entered the chat.\n");
b.setEnabled(false);
b2.setEnabled(true);
tfUsername.setEditable(false);
tfServer.setEditable(false);
tfPort.setEditable(false);
lst.add(tfUsername.getText());
tf.setEditable(true);
tf.addActionListener(this);
cc= new ThreadedChatClient(tfUsername.getText(),tfServer.getText(),por);
}
if(o==b2){
ta.append(tfUsername.getText()+" has left the chat.\n");
b.setEnabled(true);
b2.setEnabled(false);
tf.setEditable(false);
tfUsername.setEditable(true);
tfServer.setEditable(true);
tfPort.setEditable(true);
tf.removeActionListener(this);
lst.remove(tfUsername.getText());
}
if(o==tf){
DataObject objt=new DataObject(tfUsername.getText()+": "+tf.getText()+"\n");
ta.append(tfUsername.getText()+": "+tf.getText()+"\n");
tf.setText("");
}
if(o==c){
c.setBackground(Color.BLUE);
}
}
public static void main(String [] args){
ChatClientGUI cc= new ChatClientGUI("unknown","localhost",1999);
cc.setVisible(true);
}
}
Thanks in advance for your help.