TCP basic understanding issues - java

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.

Related

Java: Using AWT button to disconnect from chat server

I am programming a simple multi-threaded client/server chat system. Project requirements specify: "Connection only happens when the connect button is clicked. The disconnect button should disconnect the connection. A user should be able to connect, disconnect, re-connect at will." Basically, I have the connect button hooked-up and running. However, when I attempt to disconnect I get stuck in an infinite loop where the client side (on command line) infinitely prints "Sock closed", while the server side infinitely prints "Message read: null". This has lead me to look into all of my for(;;) loops to somehow close the connections within them, however I cannot figure out how to close the connection within those loops. Please help, this is my first socket programming project and I am super stumped on this one! Thanks all.
Client:
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
import java.util.ArrayList;
public class ClientFrame extends Frame{
public ClientFrame(){
setSize(500,500);
setTitle("Chat Client");
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent We){
System.exit(0);
}
});
add(new ClientPanel(), BorderLayout.CENTER);
setVisible(true);
}
public static void main(String[] args){
new ClientFrame();
}
} // end ClientFrame
class ClientPanel extends Panel implements ActionListener, Runnable{
TextField tf;
TextArea ta;
List list;
Button connect, disconnect;
Socket socketToServer;
PrintWriter pw;
BufferedReader br;
Thread t;
String userName;
public ClientPanel(){
setLayout(new BorderLayout());
tf = new TextField();
ta = new TextArea();
list = new List();
connect = new Button("Connect");
disconnect = new Button("Disconnect");
Panel bPanel = new Panel();
bPanel.add(connect);
disconnect.setEnabled(false);
bPanel.add(disconnect);
tf.addActionListener(this);
add(tf, BorderLayout.NORTH);
add(ta, BorderLayout.CENTER);
add(list, BorderLayout.EAST);
add(bPanel, BorderLayout.SOUTH);
connect.addActionListener(this);
disconnect.addActionListener(this);
} // end ClientPanel constructor
public void actionPerformed(ActionEvent ae){
if (ae.getSource() == tf){
String temp = tf.getText();
pw.println(userName+": "+temp);
tf.setText("");
} else if (ae.getSource() == connect){
if(tf.getText() == null || tf.getText().equals("")){
ta.append("Must enter a name to connect\n");
}else {
userName = tf.getText();
connect.setEnabled(false);
disconnect.setEnabled(true);
tf.setText("");
try{
socketToServer = new Socket("127.0.0.1", 3000);
pw = new PrintWriter(new OutputStreamWriter
(socketToServer.getOutputStream()), true);
br = new BufferedReader(new InputStreamReader
(socketToServer.getInputStream()));
}catch(UnknownHostException uhe){
System.out.println(uhe.getMessage());
}catch(IOException ioe){
System.out.println(ioe.getMessage());
}
}
t = new Thread(this);
t.start();
pw.println(userName);
pw.println(userName +" has entered the chat.");
}else if (ae.getSource()== disconnect){
try{
t.interrupt();
socketToServer.close();
}catch(IOException ioe){
System.out.println(ioe.getMessage());
}
}
} // end actionPerformed
public void run(){
for(;;){
try{
String temp = br.readLine();
ta.append(temp + "\n");
}catch(IOException ioe){
System.out.println(ioe.getMessage());
}
}
} // end run
} // end ClientPanel
Server:
import java.io.*;
import java.net.*;
import java.util.ArrayList;
import java.awt.*;
public class ThreadedServerWithPresence{
public static void main(String[] args){
ArrayList<ThreadedHandlerWithPresence> handlers;
try{
handlers = new ArrayList<ThreadedHandlerWithPresence>();
ServerSocket s = new ServerSocket(3000);
for(;;){
Socket incoming = s.accept( );
new ThreadedHandlerWithPresence(incoming,
handlers).start();
}
}catch (Exception e){
System.out.println(e);
}
}
}
class ThreadedHandlerWithPresence extends Thread{
Socket incoming;
ArrayList<ThreadedHandlerWithPresence> handlers;
PrintWriter pw;
BufferedReader br;
String userName;
public ThreadedHandlerWithPresence(Socket i,
ArrayList<ThreadedHandlerWithPresence> handlers){
incoming = i;
this.handlers = handlers;
handlers.add(this);
}
public void setUserName(String userName){
this.userName = userName;
}
public String getUserName(){
return userName;
}
public void run(){
try{
br = new BufferedReader(new InputStreamReader
(incoming.getInputStream()));
pw = new PrintWriter(new OutputStreamWriter
(incoming.getOutputStream()),true);
String firstLine = br.readLine();
setUserName(firstLine);
for(;;){
String temp = br.readLine();
System.out.println("Message read: " + temp);
for(int i = 0; i < handlers.size(); i++){
handlers.get(i).pw.println(temp);
}
}
}catch (Exception e){
System.out.println(e);
}finally{
handlers.remove(this);
}
}
}
Client
Your run method does not handle interruptions so the for loop does not end and it continues trying to receive messages.
You must add an action that can be interrupted and throws InterruptedException, Thread.sleep would be a good candidate in this case, also reducing CPU usage (You do not need to check for new messages every single moment).
try {
for (; ; ) {
try {
String temp = br.readLine();
ta.append(temp + "\n");
} catch (IOException ioe) {
System.out.println(ioe.getMessage());
}
Thread.sleep(10);
}
} catch (InterruptedException e) {
System.out.println("Disconnected.");
}
Server
When br.readLine() returns null, that indicates the connection is closed by the client and you should stop receiving messages.
String temp = br.readLine();
if(temp == null)
break;

How to make a chat program server send message to all connected clients in java

I have tried to make this program three times each time getting a little further. My program should work like this:
A client sends a message to the server which then sends the message to all connected clients (including the client that sent the message). When the clients receive the message they display it.
The problem I'm facing right now is that the server sends the message only to the client that sent it while the other clients receive nothing. I think this is happening because of the way I accept clients or at least it's somehow related to this
Here is my current code:
Client:
public class Client {
protected static JTextArea textArea = new JTextArea(20, 30);
protected static String sendMSG, getMSG;
public static void main(String[] args) throws IOException {
String hostName = args[0];
String Username = args[1];
boolean sending = true;
try (
Socket socket = new Socket(hostName, 1011);
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
) {
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
//frame setup
JFrame frame = new JFrame("chat client");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//text area
JScrollPane scrollPane = new JScrollPane(textArea);
//text field
JTextField MSGText = new JTextField(5);
//"send" button
JButton sMSGB = new JButton("send");
sMSGB.setPreferredSize(new Dimension(60, 30));
sMSGB.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
sendMSG = MSGText.getText();
MSGText.setText("");
out.println("<" + Username + ">: " + sendMSG);
}
});
//panel
JPanel p = new JPanel();
p.setLayout((new BoxLayout(p, BoxLayout.PAGE_AXIS)));
p.add(Box.createVerticalStrut(5));
p.add(scrollPane);
p.add(Box.createVerticalStrut(5));
p.add(MSGText);
p.add(Box.createVerticalStrut(5));
p.add(sMSGB);
p.add(Box.createVerticalStrut(5));
frame.getContentPane().add(p);
//set frame visible
frame.pack();
frame.setVisible(true);
System.out.println("<Client>: opened stream");
while(sending) {
/*while((sendMSG = stdIn.readLine()) != null) {
out.println("<" + Username + ">: " + sendMSG);
}*/
while((getMSG = in.readLine()) != null) {
System.out.println(getMSG);
textArea.append(getMSG + "\n");
//sending = false;
}
}
//sending = true;
}
}
}
Server:
public class Server {
public static void main(String[] args) {
try (ServerSocket serverSocket = new ServerSocket(1011)) {
boolean listening = true;
while(listening) {
Socket socket = serverSocket.accept();
List<PrintWriter> outs = new CopyOnWriteArrayList<PrintWriter>();
new ServerThread(socket, outs).start();
System.out.println("opened thread");
}
} catch(IOException e) {
e.printStackTrace();
}
}
}
ServerThread:
public class ServerThread extends Thread {
private final Socket socket;
private final List<PrintWriter> outs;
public ServerThread(Socket socket, List<PrintWriter> outs) {
super("ServerThread");
this.socket = socket;
this.outs = outs;
System.out.println("Opened outs: " + outs.size());
}
private void sendToAll(String msg) {
for(PrintWriter out: outs) {
out.println(msg);
}
}
public void run() {
try (
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
) {
System.out.println("stream opened");
outs.add(out);
String getMSGs;
while((getMSGs = in.readLine()) != null) {
//out.println(getMSGs);
sendToAll(getMSGs);
System.out.println("msg received and sent");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
I hope you can help. Thanks in advance
You're reinitializing outs every time new client connects:
while(listening) {
Socket socket = serverSocket.accept();
List<PrintWriter> outs = new CopyOnWriteArrayList<PrintWriter>();
new ServerThread(socket, outs).start();
System.out.println("opened thread");
}
and basically spawning threads with empty outs. You need to keep the list of output streams (or sockets) outside the loop and build a way to signal already existing threads when you update the outs list (when a new client connects).

Chat program using TCP : Only first message reaches other end

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();
}
}

Sending information to specific socket connection

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();}
}
}
}

Building a simple chat client

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.

Categories