Sending information to specific socket connection - java

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

Related

How do you know how to limit how many client that could enter your basic group chat app server? (Maximum 10)

so here is my code :
Server.java
import java.io.*;
import java.net.*;
import java.util.*;
class Server implements Runnable{
Socket connectionSocket;
public static Vector clients=new Vector();
public Server(Socket s){
try{
System.out.println("Client Got Connected " );
connectionSocket=s;
}catch(Exception e){e.printStackTrace();}
}
public void run(){
try{
BufferedReader reader =
new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
BufferedWriter writer=
new BufferedWriter(new OutputStreamWriter(connectionSocket.getOutputStream()));
clients.add(writer);
while(true){
String data1 = reader.readLine().trim();
System.out.println("Received : "+data1);
for (int i=0;i<clients.size();i++){
try{
BufferedWriter bw= (BufferedWriter)clients.get(i);
bw.write(data1);
bw.write("\r\n");
bw.flush();
}catch(Exception e){e.printStackTrace();}
}
}
}catch(Exception e){e.printStackTrace();}
}
public static void main(String argv[]) throws Exception{
System.out.println("Threaded Chat Server is Running " );
ServerSocket mysocket = new ServerSocket(5555);
while(true){
Socket sock = mysocket.accept();
Server server=new Server(sock);
Thread serverThread=new Thread(server);
serverThread.start();
}
}
}
mychat.java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
public class mychat implements Runnable
{
public JTextField tx;
public JTextArea ta;
public String login="Imed";
BufferedWriter writer;
BufferedReader reader;
public mychat(String l)
{
login=l;
ClientName z = new ClientName();
JFrame f=new JFrame(z.getName()+"'s Chat");
f.setSize(400,400);
JPanel p1=new JPanel();
p1.setLayout(new BorderLayout());
JPanel p2=new JPanel();
p2.setLayout(new BorderLayout());
tx=new JTextField();
p1.add(tx, BorderLayout.CENTER);
JButton b1=new JButton("Send");
p1.add(b1, BorderLayout.EAST);
ta=new JTextArea();
p2.add(ta, BorderLayout.CENTER);
p2.add(p1, BorderLayout.SOUTH);
f.setContentPane(p2);
try
{
Socket socketClient= new Socket("localhost",5555);
writer= new BufferedWriter(new OutputStreamWriter(socketClient.getOutputStream()));
reader =new BufferedReader(new InputStreamReader(socketClient.getInputStream()));
}
catch(Exception e){e.printStackTrace();}
b1.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ev)
{
String s=login+" : "+tx.getText();
tx.setText("");
try
{
writer.write(s);
writer.write("\r\n");
writer.flush();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
);
f.setVisible(true);
}
public void run()
{
try
{
String serverMsg="";
while((serverMsg = reader.readLine()) != null)
{
System.out.println("from server: " + serverMsg);
ta.append(serverMsg+"\n");
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
startclient.java
public class startclient
{
public static void main(String [] args)
{
try
{
ClientName n = new ClientName();
mychat c=new mychat(n.getName());
Thread t1=new Thread(c);
t1.start();
}
catch(Exception e){e.printStackTrace();}
}
}
And last ClientName.java
import java.util.*;
public class ClientName
{
String name;
public String getName()
{
Scanner sc = new Scanner(System.in);
System.out.print ("Enter your name : ");
name = sc.nextLine();
return name;
}
}
So basically, i want to limit how many client that could join my server(which maximum is 10 client). And if there is another client that want to join the server after it is full, that client will be rejected so it cannot joined.
I think that's it, though if there are any other improvement in other areas at my code it will also be appreciated. Sorry for my bad english
*Oh and sorry since I forget to include it, but somehow when I start the client, it ask the name twice
You can fix main method in your server and add sayGoodBye() as follows:
private static final int CONNECTION_LIMIT = 10;
public static void main(String argv[]) throws Exception {
System.out.println("Threaded Chat Server is Running ");
ServerSocket mysocket = new ServerSocket(5555);
int socketCount = 0;
while (true) {
Socket sock = mysocket.accept();
Server server = new Server(sock);
if (socketCount++ < CONNECTION_LIMIT) {
Thread serverThread = new Thread(server);
serverThread.start();
} else {
// without starting a thread and notifying only new client
server.sayGoodbye();
}
}
}
public void sayGoodbye() throws IOException {
try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(connectionSocket.getOutputStream()))) {
writer.write("Sorry, new client connections are not accepted, bye for now");
} catch (Exception e) {
e.printStackTrace();
}
connectionSocket.close();
}

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

Java error: java.net.BindException: Address already in use: JVM_Bindin server run class

When I run the client program I get this error. I checked to see if the port number is being used and already tried changing the port multiple times.
the server uses three classes:
the main and gui
class ServerGui extends Server implements ActionListener
{
public ServerGui() throws Exception
{
JFrame jfrm = new JFrame("Check in Desk");
jfrm.setLayout(new FlowLayout());
jfrm.setSize(500, 500);
jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jfrm.setVisible(true);
//menu bar
JMenuBar jmb = new JMenuBar();
JMenu jmView = new JMenu("View");
// items
JMenu jmEdit = new JMenu("Edit");
// items
JMenu jmHelp = new JMenu("Help");
// items
jmb.add(jmView);
jmb.add(jmEdit);
jmb.add(jmHelp);
//add menuBar
jfrm.setJMenuBar(jmb);
}
public void actionPerformed(ActionEvent ae)
{
String comString = ae.getActionCommand();
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
try{
new ServerGui();
}
catch(Exception e)
{
System.out.println(e + "damn");
}
}
});
}
}
The server class
public class Server extends Thread
{
public Server() throws IOException
{
this.start();
}
public void run()
{
try
{
while(true)
{
ServerSocket socketOnWhichToListenForClients= new ServerSocket(9876);
Socket socketBackToClient = socketOnWhichToListenForClients.accept();
new ClientHandler(socketBackToClient);
}
}
catch(Exception e)
{
System.out.println(e + "in server run class");
}
}
}
client handler
public class ClientHandler extends Thread
{
private Socket socketBackToClient;
public ClientHandler(Socket socket)
{
socketBackToClient = socket;
this.start();
}
public void run()
{
try
{
InputStream is = socketBackToClient.getInputStream();
BufferedReader message = new BufferedReader(new InputStreamReader(is));
String input = message.readLine();
System.out.println(input);
socketBackToClient.close();
}
catch(Exception e)
{
System.out.println("Error");
}
}
}
The client gui
public class ClientGui extends Client implements ActionListener
{
//private String name = "";
public ClientGui() throws Exception
{
name = JOptionPane.showInputDialog("Enter your name.");
if(name.equals(""))
return;
JFrame jfrm = new JFrame("Check in Desk");
jfrm.setLayout(new FlowLayout());
jfrm.setSize(300, 170);
jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jfrm.setVisible(true);
jfrm.setResizable(false);
//buttons
Font font1 = new Font("SansSerif",Font.PLAIN, 24);
Font font2 = new Font("SansSerif",Font.PLAIN, 20);
JButton jb1 = new JButton("Help");
jb1.setPreferredSize(new Dimension(100, 100));
jfrm.add(jb1);
JButton jb2 = new JButton("Check In");
jb2.setPreferredSize(new Dimension(125, 100));
jfrm.add(jb2);
jb1.setFont(font1);
jb2.setFont(font2);
//menu bar
JMenuBar jmb = new JMenuBar();
JMenu jmTools = new JMenu("Tools");
JMenuItem jmiName = new JMenuItem("Name");
JMenuItem jmiIP = new JMenuItem("Your IP");
jmTools.add(jmiName);
jmTools.add(jmiIP);
// items
JMenu jmEdit = new JMenu("Edit");
// items
JMenu jmHelp = new JMenu("Help");
JMenuItem jmiAbout = new JMenuItem("About");
jmHelp.add(jmiAbout);
// items
jmb.add(jmTools);
jmb.add(jmEdit);
jmb.add(jmHelp);
//add menuBar
jfrm.setJMenuBar(jmb);
jmiName.addActionListener(this);
jmiIP.addActionListener(this);
jb1.addActionListener(this);
jb2.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
String confirmHelp = "";
String confirmCheckIn = "";
if(ae.getActionCommand().equals("Name"))
JOptionPane.showMessageDialog(null,"Your name is " + getClientName());
if(ae.getActionCommand().equals("Your IP"))
JOptionPane.showMessageDialog(null,"Your IP is " + getIpAddress());
if(ae.getActionCommand().equals("Help"))
{
confirmHelp = JOptionPane.showInputDialog("Are You Sure You Want Help?");
if(confirmHelp != null && confirmHelp.equalsIgnoreCase("yes"))
{
Help();
}
}
if(ae.getActionCommand().equals("Check In"))
{
confirmCheckIn = JOptionPane.showInputDialog("Are You Sure You Want To Check In?");
if(confirmCheckIn != null && confirmCheckIn.equalsIgnoreCase("yes"))
{
CheckIn();
}
}
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
try{
new ClientGui();
Socket socket = new Socket(InetAddress.getLocalHost(), 9876); //new Client(); // add constructor with name or pc numb
}
catch(Exception e)
{
System.out.println("client closed");
}
}
});
}
}
The client
public class Client
{
public String name = "";
Socket clientSocket;
public Client() throws Exception
{
try
{
// clientSocket = new Socket(InetAddress.getLocalHost(), 9);
OutputStream os = clientSocket.getOutputStream();
PrintWriter pwrite = new PrintWriter(os, true);
pwrite.print("yolo");
}
catch(Exception e)
{
//System.out.println("Error cant connect"); add later
}
}
public void Help()
{
System.out.println("you pressed help");
}
public void CheckIn()
{
System.out.println("you pressed Check In");
}
public String getIpAddress()
{
String str = "";
try{
InetAddress ip = InetAddress.getLocalHost();
str = ip.toString();
}
catch(UnknownHostException e)
{
System.out.println("can not find IP address");
}
return str;
}
public String getClientName()
{
return name;
}
}
The problem is that you keep recreating the ServerSocket inside the while loop. Create it once, before the loop.
The problem is at below lines where same port is used in loop to create ServerSocket that results into below exception.
try {
while (true) {
ServerSocket socketOnWhichToListenForClients = new ServerSocket(9876);
}
} catch (Exception e) {
System.out.println(e + "in server run class");
}
Look at at the exception:
java.net.BindException: Address already in use: JVM_Bindin server run class
Don't forget to close the ServerSocket in the end. Use finally block to close it.

Java Client/Server not displaying in ClientGUI

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.

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