Wrox Programmer Forums

Need to download code?

View our list of code downloads.

Go Back   Wrox Programmer Forums > Java > Java and JDK > Java Basics
Password Reminder
Register
| FAQ | Members List | Calendar | Search | Today's Posts | Mark Forums Read
Java Basics General beginning Java language questions that don't fit in one of the more specific forums. Please specify what version.
Welcome to the p2p.wrox.com Forums.

You are currently viewing the Java Basics section of the Wrox Programmer to Programmer discussions. This is a community of tens of thousands of software programmers and website developers including Wrox book authors and readers. As a guest, you can read any forum posting. By joining today you can post your own programming questions, respond to other developers’ questions, and eliminate the ads that are displayed to guests. Registration is fast, simple and absolutely free .
DRM-free e-books 300x50
Reply
 
Thread Tools Search this Thread Display Modes
  #1 (permalink)  
Old March 29th, 2009, 04:01 AM
Registered User
 
Join Date: Mar 2009
Posts: 1
Thanks: 0
Thanked 0 Times in 0 Posts
Default java networking (server<--> all clients)

There's something wrong with the code. yes it can connect all apps but when it starts typing it only types within all clients. yeah the whole connection is like this: Server runs, clients run, clients talk to each other but not with the server, the server can talk to only one client tho [SERVER--->CLIENT<--->CLIENT]

I need the server to interact with other clients. The server need to have i/o with other clients as well as clients i/o with each other. They need to connect together. i think there's something wrong with the thread.

HELP




SERVER
Code:
import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;

public class Intercom1 extends Frame implements Runnable, ActionListener
                        
{    
   
    static Thread thread; 
    
     
    static Button btn_send,
                    btn_ok,
                    btn_connect;
                    
    static TextArea txtarea_conversation, 
                        txtarea_typehere;
                        
                        
    static Label lbl_typehere, 
                    lbl_server,
                    lbl_user,
                    lbl_usersonline,
                    lbl_conversation;
                    
    static TextField txtfld_user;
    
    static List list_usersonline;
    
    
    clientThread t[] = new clientThread[10];
    
    
    
    ServerSocket socket=null;
   
    static PrintWriter out;

    Socket insocket=null;
     
    
   
    
    
    
    

    public static void main(String[] args)
    {
        new Intercom1();
    }

    public Intercom1() 
    {
        
        
        
        setLayout(null);
        
        btn_send = new Button("SEND");
        btn_send.setBounds(385, 280, 100, 50);
        add(btn_send);
        btn_send.addActionListener(this);
        
        btn_ok = new Button("OK");
        btn_ok.setBounds(415, 39, 55, 25);
        add(btn_ok);
        btn_ok.addActionListener(this);
        
        btn_connect = new Button("CONNECT");
        btn_connect.setBounds(385, 220, 100, 25);
        add(btn_connect);
        
        txtfld_user = new TextField(20);
        txtfld_user.setBounds(295, 39, 115, 25);
        add(txtfld_user);
        
        //String[] list_usersonlineItems = {};
        list_usersonline= new List(   //list_usersonlineItems
                                       );
        list_usersonline.setBounds (385, 100, 100, 115);
        add(list_usersonline);
        
        txtarea_conversation = new TextArea("", 7, 45, 
            TextArea.SCROLLBARS_VERTICAL_ONLY);
        txtarea_conversation.setBounds(30, 100, 345, 145);
        add(txtarea_conversation);

        lbl_typehere = new Label();
        lbl_typehere.setBounds(30, 245, 100, 25);
        lbl_typehere.setText("Type here:");
        add(lbl_typehere);
        
        lbl_user = new Label();
        lbl_user.setBounds(260, 39, 40, 25);
        lbl_user.setText("User:");
        add(lbl_user);
        
        lbl_usersonline = new Label();
        lbl_usersonline.setBounds(390, 75, 100, 25);
        lbl_usersonline.setText("USERS ONLINE:");
        add(lbl_usersonline);
        
        lbl_conversation = new Label();
        lbl_conversation.setBounds(30, 75, 100, 25);
        lbl_conversation.setText("Conversation");
        add(lbl_conversation);

        txtarea_typehere = new TextArea("", 7, 45, 
            TextArea.SCROLLBARS_VERTICAL_ONLY);
        txtarea_typehere.setBounds(30, 270, 345, 70);
        add(txtarea_typehere);

        lbl_server = new Label("CHATTERBOX Server");
        lbl_server.setFont(new Font("Verdana", Font.BOLD, 16));
        lbl_server.setBounds(30, 30, 170, 40);
        lbl_server.setForeground(new java.awt.Color(136, 13, 136));
        add(lbl_server);

        setSize(509, 363);

        setTitle("CHATTERBOX");

        setVisible(true);
        txtarea_typehere.requestFocus();

        this.addWindowListener(new WindowAdapter(){
            public void windowClosing(
                WindowEvent e){
                    System.exit(0);
                    try{
                        socket.close();
                    }catch(Exception ex){}
                }
            }
        );
        
        
        //ERASE
        try {
        socket = new ServerSocket(8765);
        
        
        }
        catch (Exception e)
        {txtarea_conversation.setText(e.getMessage());}//ERASE
        
       
        /*    try 
             {    
                   socket = new ServerSocket(8765);

                insocket = socket.accept( );

                out = new PrintWriter (insocket.getOutputStream(), true);

                thread = new Thread(this);
                thread.start();
            
            }
            catch (Exception e) 
            {
                txtarea_conversation.setText(e.getMessage());
            }      
            
         */
         
         
         
         
         
         //ERASE
         while(true){
        try {
        insocket = socket.accept();
        
        
    
        for(int i=0; i<=9; i++)
            {
                if(t[i]==null)
                {   
                    
                    
                    out = new PrintWriter (insocket.getOutputStream(), true);
                    
                    (t[i] = new clientThread(insocket,t)).start();
                    
                    break;
                
                    
                }
                
            }
             
                 
        }
        catch (IOException e) {
        txtarea_conversation.setText(e.getMessage());}
    }//ERASE
    }
       
      
    
      
    public void run() 
    {
        String instring;
        try {    
       
            BufferedReader in = new BufferedReader (new 
                InputStreamReader(insocket.getInputStream()));
            while((instring = in.readLine()) != null){
                txtarea_conversation.append(instring + "\n");
            }
        }catch (IOException e) 
        {
            txtarea_conversation.setText(e.getMessage());
        } 

    }
        
    public void actionPerformed(ActionEvent event)
    {
        
        String username = txtfld_user.getText();
       
        if(event.getSource() == btn_send)
        {
            String text = txtarea_typehere.getText();
            txtarea_conversation.append(username + ": " + text +"\n");
            txtarea_typehere.setText("");
            out.println(username +": "+ text);
            txtarea_typehere.requestFocus();
        }
        
         if(event.getSource() == btn_ok)
        {
            list_usersonline.addItem(username);
            txtarea_conversation.append("\n+++ User " + username + " is now online +++\n\n");
        }
    }    
       
} 





class clientThread extends Thread{
    
    DataInputStream is = null;
    PrintStream os = null;
    Socket clientSocket = null;   
    
    clientThread t[]; 
    
    PrintWriter out;
    ServerSocket sSocket=null;    
    
    public clientThread(Socket clientSocket, clientThread[] t){
    
           
        this.clientSocket=clientSocket;
        this.t=t;
        
    }
    
    public void run() 
    {
    String line;
    String name;
    String instring; /*from clients to server*/
    
    try{
        
        
        
        is = new DataInputStream(clientSocket.getInputStream());
        os = new PrintStream(clientSocket.getOutputStream());
        
        /*  BufferedReader in = new BufferedReader (new 
                InputStreamReader(clientSocket.getInputStream()));
            while((instring = in.readLine()) != null){
                out.println(instring + "\n"); */
        
        os.println("Enter your name.");
        name = is.readLine();
        os.println("Hello "+name+" to our chat room.\n!!! To leave enter /quit in a new line !!!"); 
            
        for(int i=0; i<=9; i++)
        if (t[i]!=null && t[i]!=this)
        
            t[i].os.println("*** New user "+name+" entered the chat room !!! ***" );
            
          
            
            
        while (true) {
        line = is.readLine();
                if(line.startsWith("/quit")) break; 
        for(int i=0; i<=9; i++)
            if (t[i]!=null)  t[i].os.println("<"+name+"> "+line); 
        }
        for(int i=0; i<=9; i++)
        if (t[i]!=null && t[i]!=this)  
            t[i].os.println("*** The user "+name+" is leaving the chat room !!! ***" );
        
        os.println("*** Bye "+name+" ***"); 

        // Clean up:
        // Set to null the current thread variable such that other client could
        // be accepted by the server

        for(int i=0; i<=9; i++)
        if (t[i]==this) t[i]=null;  
        
        // close the output stream
        // close the input stream
        // close the socket
        
        is.close();
        os.close();
        clientSocket.close();
    }
    catch(IOException e){};
    }
}
///////////////////////////////////////////////////////////////////////////////

CLIENT/S
Code:
import java.io.*;
import java.awt.*;
import java.net.*;
import java.awt.event.*;

class Intercom2 extends Frame implements Runnable, ActionListener
{
    private Thread thread;
    private Button btn_ipconnect, 
                    btn_ok,
                    btn_connect,
                    btn_send;
    
    private TextArea txtarea_conversation, 
                        txtarea_typehere;
    
    private TextField txtfld_ipadd,
                        txtfld_user;
                        
    private Label lbl_serveraddress,
                    lbl_typehere, 
                    lbl_user,
                    lbl_conversation,
                    lbl_usersonline,
                    lbl_client;
                    
    private List list_usersonline;
    
    Socket socket;

    InputStream in;
    OutputStream out;
    int character;
    char[] chars = new char[1];

    public static void main(String[] args)
    {
        new Intercom2();
    }

    public Intercom2() 
    {
        setLayout(null);
        
        //String[] list_usersonlineItems = {};
        list_usersonline= new List(   //list_usersonlineItems
                                       );
        list_usersonline.setBounds (445, 135, 100, 115);
        add (list_usersonline);

        lbl_serveraddress = new Label("Server Address:");
        lbl_serveraddress.setBounds(260, 39, 95, 15);
        add(lbl_serveraddress);
        
        lbl_conversation = new Label("CONVERSATION");
        lbl_conversation.setBounds(15, 105, 100, 25);
        add(lbl_conversation);
        
        lbl_usersonline = new Label("USERS ONLINE:");
        lbl_usersonline.setBounds(450, 110, 94, 20);
        add(lbl_usersonline);
        
        lbl_user = new Label("User:");
        lbl_user.setBounds(317, 67, 35, 15);
        add(lbl_user);

        txtfld_ipadd = new TextField("122.3.214.141");
        txtfld_ipadd.setBounds(355, 39, 115, 20);
        add(txtfld_ipadd);
        
        txtfld_user = new TextField("");
        txtfld_user.setBounds(355, 67, 115, 20);
        add(txtfld_user);

        btn_ipconnect = new Button("Connect");
        btn_ipconnect.setBounds(474, 37, 85, 20);
        add(btn_ipconnect);
        btn_ipconnect.addActionListener(this);
        
        btn_ok = new Button("OK");
        btn_ok.setBounds(474, 66, 85, 20);
        add(btn_ok);
        btn_ok.addActionListener(this);
        
        btn_connect = new Button("CONNECT");
        btn_connect.setBounds(445, 260, 100, 25);
        add(btn_connect);
        btn_connect.addActionListener(this);

        btn_send = new Button("SEND");
        btn_send.setBounds(445, 325, 100, 50);
        add(btn_send);
        btn_send.addActionListener(this);

        txtarea_conversation = new TextArea("", 7, 45, 
            TextArea.SCROLLBARS_VERTICAL_ONLY);
        txtarea_conversation.setBounds(15, 135, 410, 145);
        add(txtarea_conversation);

        lbl_typehere = new Label();
        lbl_typehere.setBounds(15, 290, 100, 25);
        lbl_typehere.setText("Type here:");
        add(lbl_typehere);

        txtarea_typehere = new TextArea("", 7, 45, 
            TextArea.SCROLLBARS_VERTICAL_ONLY);
        txtarea_typehere.setBounds(15, 315, 410, 65);
        add(txtarea_typehere);

        lbl_client = new Label("CHATTERBOX Client");
        lbl_client.setFont(new Font("Verdana", Font.BOLD, 16));
        lbl_client.setBounds(20, 40, 170, 40);
        lbl_client.setForeground(new java.awt.Color(1,1,112));
        add(lbl_client);

        setSize(575, 395);

        setTitle("Intercom 2");
        setVisible(true);
        txtarea_typehere.requestFocus();

        this.addWindowListener(new WindowAdapter(){
            public void windowClosing(
                WindowEvent e){
                    System.exit(0);
                }
            }
        );
    }

    public void run() 
    {
        try{
            while ((character = in.read()) != -1) {
                chars[0] = (char)character;
                txtarea_conversation.append(new String(chars));
            }
        }
        catch(Exception ex)
            {txtarea_conversation.setText(ex.getMessage());}
    }

    public void actionPerformed(ActionEvent event)
    {
        if(event.getSource() == btn_ipconnect){
            try{
                socket = new Socket(txtfld_ipadd.getText(), 8765);
                txtfld_ipadd.setText("Connecting....");

                in = socket.getInputStream();
                out = socket.getOutputStream();
                
                thread = new Thread(this);
                thread.start(); 
            }
            catch (IOException ioe){
                txtarea_conversation.setText("Intercom 1 must be running and\n"
                + "accessible before running Intercom 2.\n");
                txtfld_ipadd.setText("Not connected");
            }
            catch (Exception e){
                txtarea_conversation.setText(e.getMessage());
            }

            if(socket != null && socket.isConnected())
            {
                txtfld_ipadd.setText("Connected");
                 
                 
            }
        }

        if(event.getSource() == btn_send){
            try{
                String str = txtarea_typehere.getText() + "\n";
                byte buffer[] = str.getBytes();
                out.write(buffer);
                txtarea_typehere.setText("");
                txtarea_typehere.requestFocus();
            }
            catch(Exception ex)
                {txtarea_conversation.setText(ex.getMessage());}
        }
    }
}
Reply With Quote
  #2 (permalink)  
Old April 1st, 2009, 12:28 AM
Friend of Wrox
 
Join Date: Mar 2007
Location: Hyderabad, A.P., India.
Posts: 373
Thanks: 0
Thanked 1 Time in 1 Post
Default

Hi,

In the infinite loop where you accept connections from clients you've a line

Code:
  out = new PrintWriter (insocket.getOutputStream(), true);
This 'out' object always refers to the output stream of the last client connected. So when server tries to send text it is using this 'out' object, which will only be sent to the last client connected.

Hope this gives clue to solve your problem.
__________________
- Rakesh
http://iam-rakesh.blogspot.com
Reply With Quote
Reply


Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off
Trackbacks are Off
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
<style> tags in a <body> vs. <div> bcat BOOK: Beginning CSS: Cascading Style Sheets for Web Design ISBN: 978-0-7645-7642-3 1 March 27th, 2005 08:50 AM
<marquee><b>About CHAT App. in PHP4</b></marquee> Ramkrishna PHP How-To 1 September 11th, 2004 07:01 AM
<STRONG> vs <B> and <EM> vs <I> anshul HTML Code Clinic 12 September 1st, 2004 05:22 PM
Using Java Applets and the <object> tag Alexpizzoferro HTML Code Clinic 5 May 25th, 2004 07:55 PM
The code of <Oracle 9I Java Programming> One Wrox Book Feedback 5 April 14th, 2004 08:04 AM



All times are GMT -4. The time now is 09:57 AM.


Powered by vBulletin®
Copyright ©2000 - 2019, Jelsoft Enterprises Ltd.
© 2013 John Wiley & Sons, Inc.