Socket Based Server/Client Program Help Needed

Alright,
I am making a Client/Server program.
The idea is that, when I run the 'Server' part, it sits and listens for a connection from the Client.
The Client writes a string to the socket, then the server, interprets the command.
This is what I have so far.
The Server:
public static void main(String[] args) {
         String clientLine = null;
          Socket channel = new Socket();
          try {
               mainWin window = new mainWin();
               window.open();
          } catch (Exception e) {
               e.printStackTrace();
         try{
               ServerSocket server = new ServerSocket(8313);
              BufferedReader reader = new BufferedReader(new InputStreamReader(channel.getInputStream()));
             channel = server.accept();
             clientLine = reader.readLine();
             doCommand(clientLine);
             reader.close();
             channel.close();
             server.close();
         catch(IOException ioe){
              System.out.println("I/O Exception occurred while using the server");
     }The Client:
public void sendCommand(String command){
          PrintStream socketWriter  = null;
          try{
                Socket client = new Socket("127.0.0.1", 8313);
                socketWriter = new PrintStream(client.getOutputStream());
                socketWriter.println(command);
                socketWriter.close();
                client.close();
          }catch(UnknownHostException uhe){
          }catch(IOException ioe){
     }When I press the command button, it lags for a second, then does nothing.
Does anyone see the problem?

public static void main(String[] args) {
         String clientLine = null;
          Socket channel = new Socket(); //<-- This is connecting to where? nowhere, so initiate it to null instead.
          try {
               mainWin window = new mainWin();
               window.open();
          } catch (Exception e) {
               e.printStackTrace();
         try{
               ServerSocket server = new ServerSocket(8313);
              BufferedReader reader = new BufferedReader(new InputStreamReader(channel.getInputStream())); //<-- Getting an input stream from nowhere?
             channel = server.accept(); //<-- Perhaps you want to do this before you try to get the input stream from it?
             clientLine = reader.readLine();
             doCommand(clientLine);
             reader.close();
             channel.close();
             server.close();
         catch(IOException ioe){
              System.out.println("I/O Exception occurred while using the server");
     }

Similar Messages

  • Server / client program help

    Was hoping someone could give me advice on some coding im trying to do for uni.
    To give you an overall view: im trying to create a little inventory program where there is a server interface and a client interface. Now on the client interface it displays a menu with several options and the server interface displays whats in the repository. Upon choosing one of those options it sends the appropriate method request to the server handler. What im trying to do is add a function where i can dynamically add items to the repository. This is already in place from the code i have from uni using the server.put class and method. however i cant seem to add them to it
    I have botched together this method which i think will add new items to the repository:
    public String addItem(){
        String serialNo = (String) receive();
        String description = (String) receive();
        Integer stock = (Integer) receive();
        String location = (String) receive();
        //String dateTime = (String) receive();
        //creates new stockitem from stockitem class
        StockItem item = new StockItem(serialNo, description, stock, location) ;
        // creates new serial number
        serialNo = new Integer(server.getReposSize() + 1).toString();
        //Must make item code unique to this client
        serialNo = serialNo + this.hashCode();
        while (server.exists(serialNo)){
        serialNo = new Integer(server.getReposSize() + 1).toString();
    server.put(serialNo, item);
    return "Item added";
    }So above i hope the method will recieve the data input on the client interface and then use "server.put" to input the recieved data into the server repository and to display it in the server interface.
    Now on the client side i have added code to send the serialno, description,stock and location. Shown below:
    if (choice.equals("n")){
            //Add new Item
            send("addItem"); // remote method
            //Send Serial Number
            System.out.println("Item Serial no.\t");
            String serialNo = getString();
            send (new Integer(serialNo));
            // send description
            System.out.println("Item Description\t");
            String description = getString();
            send(new String(description));
            //Send No. of STock
            System.out.println("No. Of Stock\t");
            String stock = getString();
            send (new Integer(stock));
            // send Item Location
            System.out.println("Item Location\t");
            String location = getString();
            send(new String(location));
            send(getDateTime());         //Time of transaction
            System.out.println(receive());      //Find out the status of our command
            }So above should send this from the client interface to the server which should recieve it.
    But my problem is how do i insert the data sent by the user into the server repository? I thought this would work by using "server.put(serialNo, item);" in the first method shown but it doesnt seem to work?
    As you can see from the first "additem" method there is a "server.put" which relates to a method in the server class which adds things to the repository. ive looked in the server class and noticed the put method has only two objects. Originally i was trying to fit the 4 objects (serial description,location and stock) in there but as you can see from my first method i have tried inserting just two of these and they still dont show in the server interface.
    Here is the snappit from the server class:
    public synchronized void put(Object key,Object item){
        repos.put(key,item);
        hci.updateObjects(repos,locked);
        }Any idea's on this? SOrry if im vague im not too familar with the correct terminology im still getting the hang of it all! I have however statically defined some test items in my code and it shows in the server interface OK but when i send them dynamically they do not work.
    Thanks

    Any idea's? im stumped at the moment.

  • Need an example of server / client program with swing interface

    Hi!
    After a lot of trying i still haven't managed to create a server client program using swing components ...
    can someone write a mini application to demonstrate how this can be done?
    i would like to have a frame with a button a texField for input and a textAread for the output
    What i have in mind is the following ..
    say im the server
    i write something in the textField and then i press the button
    then the information written in the textFiled is passed to the client who shows it in his textArea
    The same thing goes on with the client (he can write something in his own textField and when he presses the button the info is passed at the
    server who puts it in his textArea) and vice versa.
    i have written many classes that trying unsuccessfully to do that ... below i show my last attempt ...
    I would appreciate if you could write a small application which it could to this.
    The whole idea is to create a turn based game ( i have implemented the game engine and graphics and i try to add the internet function)
    Here is the code ...( i would appreciate if you write a new code instead of trying to correct mine ( which i think it's impossible) in order to use it as a general example)
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    @SuppressWarnings("serial")
    *  In order to have a more gereral program instead of passing strings between the server
    *  and the client a pass an MyObjext object.  The MyObject class has an integer and a String
    *  (which is always the same) field . At the textField i write an integer number and i
    *  make a new MyObject which i want to pass to the server or the client and vice versa.
    *  The textArea shows the integer value of the MyObject which was passed from the server /client
    public class MyUserInterface extends JFrame {
         MyObject returnObject;
         JTextField myTextField;
         JTextArea te ;
         ClientGame cg;
         ServerGame sg;
          * used to determine if the current instance is running as a client or host
         boolean isHost;
         //The constructor of the client
         public MyUserInterface(ClientGame cg){
              this("Client");
              this.cg = cg;
              isHost = false;
         //The constructor of the server
         public MyUserInterface(ServerGame sg){
              this("Server");
              this.sg = sg;
              isHost = true;
         //The general constructor used both by client and server ..
         // it initializes the GUi components and add an actionListenr to the button
         public MyUserInterface(String str) {
              super(str);
              myTextField = new JTextField(2);
              te = new JTextArea();
              te.setPreferredSize(new Dimension(100,100));
              JButton okButton = new JButton("Ok");
              okButton.addActionListener(new ActionListener() {
                   @Override
                   public void actionPerformed(ActionEvent e) {
                        try{
                             int a = Integer.parseInt(MyUserInterface.this.myTextField.getText());
                             System.out.println(a);   //used to control the flow of the program
                                  MyUserInterface.this.returnObject = new MyObject(a);
                             //sends the data
                             sendData();
                             //waiting for response...
                             getData();
                             catch(Exception ex){System.out.println("Error in the UI action command" +
                                                                ex.printStackTrace();}
              JPanel panel =  new JPanel(new FlowLayout());
              panel.add(okButton);
              panel.add(myTextField);
              panel.add(te);
              setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              getContentPane().add(panel);
              pack();
              setVisible(true);
         protected MyObject getReturnObject() {
              return returnObject;
         public void sendData(){
              new Thread(new Runnable() {
                   @Override
                   public void run() { 
                        if (!isHost)cg.sentData(returnObject);    //using the Servers out and in methods
                        else sg.sentData(returnObject);                    //using the Clients out and in methods
                        System.out.println("data sending");
         public MyObject getData(){
              MyObject obj;
              System.out.println("Retrieveing Data");
              if (!isHost)obj = (MyObject)cg.getData();
              else obj = (MyObject)sg.getData();
              System.out.println(" data retrieved  = "+ obj.getInt());  //just to control how the code flows
              te.setText(obj.getInt()+"");       
              return obj;
         public static void main(String[] args) {
              *Initiating the Server
              new Thread(new Runnable() {
                   @Override
                   public void run() {
                        ServerGame sg = new ServerGame();
                        new MyUserInterface(sg);
              }).start();     
               * Initiating the Client
              new Thread(new Runnable() {
                   @Override
                   public void run() {
                        ClientGame cg = new ClientGame("192.168.178.21");   //<----in case you run my code
                                                                          //..don't forget to change to your
                        new MyUserInterface(cg);                              //ip
              }).start();
    import java.io.*;
    import java.net.*;
    public class ClientGame {
         String ipAddress;
         Socket clientSocket = null;
        ObjectOutputStream out = null;
        ObjectInputStream in = null;
         public ClientGame(String ipAddress) {
              this.ipAddress = ipAddress;
              try {
                   System.out.println("Connecting To Host");
                 clientSocket = new Socket(InetAddress.getByName(ipAddress),4444);
                System.out.println("Host Found ...Io initializaton");
                out = new ObjectOutputStream(clientSocket.getOutputStream());
                in = new ObjectInputStream(clientSocket.getInputStream());
            } catch (UnknownHostException e) {
                System.err.println("Don't know about host: taranis.");
                System.exit(1);
            } catch (IOException e) {
                System.err.println("Couldn't get I/O for the connection to: taranis.");
                System.exit(1);
         public Object getData(){
              Object fromServer = null ;
              do{
                 try {
                      fromServer = in.readObject();
                 catch(ClassNotFoundException ex){}
                  catch(IOException e){}
              }while(fromServer==null);
              return fromServer;        
         public void sentData(final Object obj){
              new Thread(new Runnable() {
                   @Override
                   public void run() {
                        try{
                             out.writeObject(obj);
                        catch(IOException e){}
              }).start();
         public void terminateConnection(){
              try{
                   out.close();
                   in.close();
                   clientSocket.close();
              catch (IOException e){}
    public class ServerGame {
         ServerSocket serverSocket;
         Socket clientSocket;
         ObjectOutputStream out = null;
        ObjectInputStream in = null;
         public ServerGame() {
              try{
                   serverSocket = new ServerSocket(4444);
                   clientSocket = serverSocket.accept();
                   out =  new ObjectOutputStream(clientSocket.getOutputStream());
                in = new ObjectInputStream(clientSocket.getInputStream());
              catch(IOException e){System.out.println("IOException in ServerGame");}
         public Object getData(){
              Object fromClient = null ;
              do{
                 try {
                      fromClient = in.readObject();
                 catch(ClassNotFoundException ex){}
                  catch(IOException e){}
              }while(fromClient==null);
             return fromClient;        
         public void sentData(final Object obj){
              new Thread(new Runnable() {
                   @Override
                   public void run() {
                        try{
                   out.writeObject(obj);
              catch(IOException e){}
              }).start();
         public void terminateConnection(){
              try{
                   out.close();
                   in.close();
                   clientSocket.close();
                   serverSocket.close();
              catch (IOException e){}
         public static void main(String[] args) {
              new ServerGame();
    import java.io.Serializable;
    * this is a test object
    * it has a String field and a value
    *  The string is always the same but the integer value is defined in the constructor
    public class MyObject implements Serializable{
         private static final long serialVersionUID = 1L;
         String str;
         int myInt;
         MyObject(int a){
              str = "A String";
              myInt = a;
         public int getInt(){
              return myInt;
    }

    Pitelk wrote:
    I believe that a good code example can teach you things ;that you would need many days of searching; in no timeSo lets write one small example.. Ill help a little, but you do most of the work.
    jverd approach is deffenetly the way to go.
    jverd wrote:
    * Write a very small, simple Swing program with an input area, an output area, and a button. When you click the button, what's in the input area gets copied over to the output area.This part is partially done.
    * Write a very small, simple client/server program without Swing. It should just send a couple of hardcoded messages back and forth.And this part is for you(Pitelk) to continue on. I cannot say that this is the best way. or that its good in any way. I do however like to write my client/server programs like this. And perhaps, and hopefully, Ill learn something new from this as well.
    This is how far I got in about 10-20min..
    package client;
    * To be added;
    * A connect method. That connects the client to the server and
    * opens up both the receive and transmit streams. After doing that
    * the an instance of the ServerListener class should be made.
    * Also an disconnect method could be usable. But thats a later part.
    public class TestClass1 {
    package utils;
    import java.io.ObjectInputStream;
    import client.TestClass1;
    * This class is meant to be listening to all responses given from
    * the server to the client. After a have received data from the
    * server. It should be forwarded to the client, in this case
    * TestClass1.
    public class ServerListener implements Runnable {
         public ServerListener(ObjectInputStream in, TestClass1 tc) {
         @Override
         public void run() {
              while(true) {
    package server;
    import java.io.ObjectOutputStream;
    import java.net.Socket;
    import java.util.ArrayList;
    import java.util.List;
    * This class should handle all data sent to the server from the clients.
    class Server implements Runnable {
         private static List<ObjectOutputStream> outStreams = new ArrayList<ObjectOutputStream>();
         private Socket client = null;
         public Server(Socket client) {
              this.client = client;
         @Override
         public void run() {
              while(true) {
    * The meaning of this class is to listen for clients trying to connect
    * to the server. Once connection is achieved a new thread for that client
    * should be made to listen for data sent by the client to the server.
    public class ChatServer implements Runnable {
         @Override
         public void run() {
              while(true) {
    package utils;
    import java.io.Serializable;
    @SuppressWarnings("serial")
    public class MyObject implements Serializable {
         private String mssg;
         private String clientID;
         private String clientName;
         public MyObject(String mssg, String clientID, String clientName) {
              this.mssg = mssg;
              this.clientID = clientID;
              this.clientName = clientName;
         //Generate getters and setters..
    }Continue on this, and when you get into problems etc post them. Also show with a small regular basis how far you have gotten with each class or it might be seen as you have lost intresst and then this thread is dead.
    EDIT: I should probably also say that Im not more than a java novice, at the verry most. So I cannot guarantee that I alone will be able to solve all the problems that might occure during this. But Im gonna try and help with the future problems that may(most likely will) occure atleast(Trying to reserve my self incase of misserable failiure from me in this attempt).
    Edited by: prigas on Jul 7, 2008 1:47 AM

  • My first Server/Client Program .... in advise/help

    Hello,
    I am learning about Sockets and ServerSockets and how I can use the. I am trying to make the simplest server/client program possible just for my understanding before I go deper into it. I have written two programs. theserver.java and theclient.java the sere code looks like this....
    import java.net.*;
    import java.io.*;
    import java.util.*;
    public class theserver
      public static void main(String[] args)
      {   //  IOReader r = new IOReader();
            int prt = 3333;
            BufferedReader in;
             PrintWriter out;
            ServerSocket serverSocket;
            Socket clientSocket = null;
    try{
    serverSocket = new ServerSocket(prt);  // creates the socket looking on prt (3333)
    System.out.println("The Server is now running...");
    while(true)
        clientSocket = serverSocket.accept(); // accepts the connenction
        clientSocket.getKeepAlive(); // keeps the connection alive
        out = new PrintWriter(clientSocket.getOutputStream(),true);
        in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
         if(in.ready())
         System.out.println(in.readLine()); // print it
    catch (IOException e) {
        System.out.println("Accept failed:"+prt);
    and the client looks like this
    import java.net.*;
    import java.io.*;
    public class theclient
    public static void main(String[] args)
        BufferedReader in;
        PrintWriter out;
        IOReader r = new IOReader();
        PrintWriter sender;
        Socket sock;
      try{
        sock = new Socket("linuxcomp",3333);  // creates a new connection with the server.
        sock.setKeepAlive(true); // keeps the connection alive
        System.out.println("Socket is connected"); // confirms socket is connected.
        System.out.println("Please enter a String");
         String bob = r.readS();
          out = new PrintWriter(sock.getOutputStream(),true);
        out.print(bob); // write bob to the server
      catch(IOException e)
           System.out.println("The socket is now disconnected..");
    If you notice in the code I use a class I made called IOReader. All that class is, is a buffered reader for my System.in. (just makes it easier for me)
    Ok now for my question:
    When I run this program I run the server first then the client. I type "hello" into my system.in but on my server side, it prints "null" I can't figure out what I am doing wrong, if I am not converting correctly, or if the message is not ever being sent. I tried putting a while(in.read()) { System.out.println("whatever") } it never reaches a point where in.ready() == true. Kinda of agrivating. Because I am very new to sockets, I wanna aks if there is somthing wrong with my code, or if I am going about this process completely wrong. Thank you to how ever helps me,
    Cobbweb

    here's my simple server/client Socket :
    Server:
    import java.net.*;
    import java.io.*;
    public class server
       public static void main(String a[])
              ServerSocket server=null;
              Socket socket=null;
              DataInputStream input=null;
              PrintStream output=null;
          try
             server=new ServerSocket(2000);
             socket=server.accept();
             input = new DataInputStream(socket.getInputStream());
             output = new PrintStream(socket.getOutputStream());
             //output.println("From Server: hello there!");
             String msg="";
             while((msg=input.readLine()) != null)
                System.out.println("From Client: "+msg);
          catch(IOException e)
          catch(Exception e)
    }Client:
    import java.net.*;
    import java.io.*;
    public class client
       static private Socket socket;
       static private DataInputStream input;
       static private PrintStream output;
       public static void main(String a[])
          try
    socket=new Socket("10.243.21.101",2000);
    System.out.println("\nconnected to: \""+socket.getInetAddress()+"\"");
             input=new DataInputStream(socket.getInputStream());
             output=new PrintStream(socket.getOutputStream());
             output.println("From Client(Tux): "+a[0]);
             String msg="";
             //while((msg=input.readLine()) != null)
                 System.out.println("From Server(Bill): "+msg);
          catch(java.io.IOException e)
          catch(Exception e)
    }

  • RTP Server/ Client Program using JMF Library

    Hi folks,
    I am trying to send A/V data from Camcorder(SONY DCR-PC115) to PC(Red Hat Linux 7.3 kernal version 2-18.3), and then send that data to clinet programm via a network ( i.e. A/V data should be delivered by network using RTP/RTCP Protocol).
    I guess I need to make RTP Server and RTP Client program, and using JMF library in order to send data with RTP Protocol. Isn't it?
    So what I want here is Do any body have idea/experiance in making RTP Clinet /Server program using JMF library then pls let me know
    my e-mail id is [email protected], [email protected]
    Many thanks
    looking forward to hear from you soon
    Regards
    Madhu Chundu

    Hi,
    I'm also working on the same type of problem, so if anyone has already worked or have an idea of how it works or does, please mail me the details to my mail-id: [email protected]
    Thanks In Advance,
    Rajanikanth Joshi

  • Server/Client Programs

    Can somebody give me advice on writing a program that a client reads from a text file and sends the data to a server which in turn does math operations or strign operations on the data .....then sends the new file back to the client to be displayed.Thanks

    Here is some code that implements a very rudimentary
    client/server relationship. import java.util.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class Client extends JFrame implements ActionListener
         private JTextArea jta;
         private void init()
              addWindowListener(new WindowAdapter()     {
                   public void windowClosing(WindowEvent e) {
                        System.exit(0);
              setSize(300, 200);
              jta = new JTextArea(20, 40);
              JPanel jp = new JPanel(new FlowLayout());
              JButton jbOK = new JButton("OK");
              jbOK.addActionListener(this);
              jp.add(jbOK);
              JButton jbDone = new JButton("Done");
              jbDone.addActionListener(this);
              jp.add(jbDone);
              getContentPane().add(jp, BorderLayout.SOUTH);
              getContentPane().add(jta);
              show();
         void setData(String s)
              jta.setText(s);
         public void actionPerformed(ActionEvent ae)
              if (ae.getActionCommand().equals("Done")) {
                   System.exit(0);
    // Call your input routine here and pass the result to Server instead of the String from the JTextArea
              Server s = new Server(this, jta.getText());            
    s.compress();
         public static void main(String args[])
              Client c = new Client();
              c.init();
    class Server
         String s;
         Client c;
         public Server(Client passer, String pass)
              s = pass;
              c = passer;
         void compress()
              StringTokenizer st = new StringTokenizer(s);
              String n = "";
              while(st.hasMoreTokens()) {
                   n += st.nextToken();
              c.setData(n);
    }This should get you started.
    Mark

  • SOCKET PROGRAMMING  HELP NEEDED!!!!

    hi,
    I got an idea of establishing socket connection with all clients from SERVER through the windows command
    called (arp -a). when we type the stated command on dosprompt in server, it gives the list of current system's
    ipaddress.....switched on. SO i can establish socket connections in a for loop where i can take the following ipaddress from output listed from command.
    i've written the code to call the command in JAVA.
    i write the dosprompt output in a file named list1.txt
    import java.util.*;
    import java.io.*;
    import java.io.File;
    public class RunCommand
    public static String[] runCommand(String cmd) throws IOException
    ArrayList list = new ArrayList();
    Process proc = Runtime.getRuntime().exec(cmd);
    InputStream istr = proc.getInputStream();
    BufferedReader br = new BufferedReader(new InputStreamReader(istr));
    String str;
    while ((str = br.readLine()) != null)
    list.add(str);
    try
    proc.waitFor();
    }catch (InterruptedException e)
    System.err.println("process was interrupted");
    // check its exit value
    if (proc.exitValue() != 0)
    System.err.println("exit value was non-zero");
    // close stream
    br.close();
    // return list of strings to caller
    return (String[])list.toArray(new String[0]);
    public static void main(String[] args) throws Exception
    try
    FileWriter f1=new FileWriter("list1.txt");
    String[] s = runCommand("arp -a");
    for (int i = 0; i< s.length; i++)
    f1.write(s);
    System.out.println(s[i]);
    f1.close();
    }catch (Exception ex) { System.out.println(ex);}
    SAMPLE OUTPUT:
    Interface: 172.16.3.1 on Interface 0x1000003
    Internet Address Physical Address Type
    172.16.3.4 00-00-e2-13-a9-e8 dynamic
    172.16.3.6 00-00-e2-13-aa-0f dynamic
    172.16.3.10 00-00-e2-13-ab-bb dynamic
    172.16.3.12 00-00-e2-13-ab-93 dynamic
    172.16.3.16 00-00-e2-13-37-b8 dynamic
    172.16.3.17 00-00-e2-13-37-19 dynamic
    172.16.3.18 00-00-e2-13-37-1d dynamic
    172.16.3.19 00-00-e2-13-38-98 dynamic
    172.16.3.22 00-00-e2-13-37-54 dynamic
    172.16.3.23 00-00-e2-13-39-02 dynamic
    172.16.3.24 00-00-e2-13-39-0f dynamic
    172.16.3.26 00-00-e2-13-37-a5 dynamic
    172.16.3.27 00-00-e2-13-37-0b dynamic
    172.16.3.28 00-00-e2-13-37-12 dynamic
    172.16.3.29 00-00-e2-13-39-15 dynamic
    172.16.3.30 00-00-e2-13-38-af dynamic
    172.16.3.31 00-00-e2-13-37-fe dynamic
    172.16.3.32 00-00-e2-13-38-ff dynamic
    172.16.3.34 00-00-e2-13-ab-c8 dynamic
    172.16.3.37 00-00-e2-13-ab-67 dynamic
    172.16.3.42 00-00-e2-13-ab-19 dynamic
    PLS HELP ME OUT IN GETTING ONLY THE IPADDRESS IN FOR LOOP IN SERVER SOCKET PROGRAM TO INVOKE ALL CLIENT'S PROGRAM IN NETWORK.
    PLS HELP ME!!!!!!!
    ATTACH THE CODE!!!!!!!!!!!!

    Connecting to a client presumes that the client is waiting for a connection.
    If that is the case I would suggest looking a java.net.Socket.

  • Multithreading server /- client doesnt update need a little help

    I have three classes, one is my client called lobby, the second is my server, then my third is the server thread. Everything works but the client doesnt seem to update unless you type stuff in and hit enter or press send and that isbecause of the key and action listeners, how do i go about having to updating every 10 seconds or less..? I tried doing a while statement and of course it freezed it because its an infinite loop, tried making it a thread, not to good at that, i just need some advice on how to solve this problem, thanks.
    public class Lobby extends JPanel {
         public Lobby()
              listenSocket();
              send = new JButton("Send");
              chatter = new JTextField();
              motd = new JLabel("The Lobby");
              this.setLayout(new MigLayout());
              this.setSize(800, 600);
              this.setBackground(Color.white);
              this.setAutoscrolls(true);
              this.add(motd, "span 1, align center");
              this.add(UserListTop(), "align center, wrap");
              this.add(ChatBox(), "");
              this.add(UserList(), "wrap");
              this.add(Chatter(), "");
              this.add(Send(), "");
              this.setVisible(true);
         public Component ChatBox()
              Dimension dscroll = new Dimension(590, 400);
              chatbox = new JTextArea(20, 50);
              chatbox.setLineWrap(true);
              chatbox.setEditable(true);
              chatbox.setWrapStyleWord(true);
              JScrollPane areaScrollPane = new JScrollPane(chatbox);
              areaScrollPane.setVerticalScrollBarPolicy(
                        JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
              areaScrollPane.setAutoscrolls(true);
              areaScrollPane.setPreferredSize(dscroll);
              return areaScrollPane;
         public Component Chatter()
              KeyListener enter = new KeyListener()
                   @Override
                   public void keyPressed(KeyEvent event) {
                        if((event.getKeyChar() == KeyEvent.VK_ENTER) && (chatter.getText() != "") && (chatter.getText() != null))
                             //Send data over socket
                             String text = chatter.getText();
                             out.println(text);
                             chatter.setText(new String());
                             //Receive text from server
                             try{
                                  String line = in.readLine();
                                  chatbox.append("Usernamehere: " + line + "\n");
                             } catch (IOException e){
                                  System.out.println("Read failed");
                                  System.exit(1);
                   @Override
                   public void keyReleased(KeyEvent e) {
                   @Override
                   public void keyTyped(KeyEvent e) {
              String line;
              try {
                   line = in.readLine();
                   chatbox.append("usernamehere: " + line + "\n");
              } catch (IOException e1) {
                   // TODO Auto-generated catch block
                   e1.printStackTrace();
              chatter.addKeyListener(enter);
              Dimension chattersize = new Dimension(590, 30);
              chatter.setPreferredSize(chattersize);
              chatter.setVisible(true);
              return chatter;
         public Component Send()
              ActionListener sendl = new ActionListener()
                   @Override
                   public void actionPerformed(ActionEvent event) {
                        Object source = event.getSource();
                        if(source == send){
                             //Send data over socket
                             String text = chatter.getText();
                             out.println(text);
                             chatter.setText(new String(""));
                             //Receive text from server
                             try{
                                  String line = in.readLine();
                                  System.out.println("UserNameHere: " + line);
                                  chatbox.append("Usernamehere: " + line + "\n");
                             } catch (IOException e){
                                  System.out.println("Read failed");
                                  System.exit(1);
              send.addActionListener(sendl);
              send.setVisible(true);
              return send;
         public Component UserListTop()
              JLabel userlisttop = new JLabel("Players");
              return userlisttop;
         public Component UserList()
              Dimension scrollsize = new Dimension(170, 400);
              String names[] = new String[1500];
              for(int i = 0; i < 1500; i++)
                   names[i] = "Player" + i;
              userlist = new JList( names );
              userlist.setBackground(Color.white);
              userlist.setSize(50, 200);
              JScrollPane userlistscroll = new JScrollPane(userlist);
              userlistscroll.setPreferredSize(scrollsize);
              return userlistscroll;
         public void listenSocket(){
              //Create socket connection
              try{
                   socket = new Socket("localhost", 4444);
                   out = new PrintWriter(socket.getOutputStream(), true);
                   in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
              } catch (UnknownHostException e) {
                   System.out.println("Unknown host: localhost");
                   System.exit(1);
              } catch  (IOException e) {
                   System.out.println("No I/O");
                   System.exit(1);
    }

    3rd class
    package server;
    import java.io.DataInputStream;
    import java.io.IOException;
    import java.io.PrintStream;
    // This client thread opens the input and the output streams for a particular client,
    // ask the client's name, informs all the clients currently connected to the
    // server about the fact that a new client has joined the chat room,
    // and as long as it receive data, echos that data back to all other clients.
    // When the client leaves the chat room this thread informs also all the
    // clients about that and terminates.
    import java.net.Socket;
    public class clientThread extends Thread{
        DataInputStream is = null;
        PrintStream os = null;
        Socket clientSocket = null;      
        clientThread t[];
        public clientThread(Socket clientSocket, clientThread[] t){
         this.clientSocket=clientSocket;
            this.t=t;
        public void run()
         String line;
            String name;
         try{
             is = new DataInputStream(clientSocket.getInputStream());
             os = new PrintStream(clientSocket.getOutputStream());
             os.println("Enter your name.");
             name = is.readLine();
             os.println("Hello "+name+" to our chat room.\nTo leave enter /quit in a new line");
             for(int i=0; i<=9; i++)
              if (t!=null && t[i]!=this)
              t[i].os.println("*** A 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){};

  • Server/Client program to work with a handheld windows device and a laptop

    Hi, I am trying to develop a program for work. I basically need to test the life of a handheld device by essentially having the device "ping" a server. I need the device (Client) to make a connection to the server, and if it works, I want it to write out to the server the time. Every thing that I have tried has failed, so far. I have experience with Java, but not a whole lot in Networking. I am still a student (and a lowly one at that). Can anyone help me with this? Should I use an applet? A socket? I'm not even really sure how to go about doing this.
    Thanks,
    Shawna

    Okay, the device is a scanning device used in warehouses. It has Windows CE 5. I'm trying to get in contact with the person that manages these handhelds to make sure that they support Java. Assuming they do, however, What do you believe is my best option? .Net was the preferred language, but I was having too much trouble trying to get Visual Studio on to my laptop computer, which I use for work, and I also don't have any experience using .Net. I tried creating Sockets, but I don't think I did it correctly. The only thing I have to go off of is an Introduction to Java book that I use for school, and the examples don't really help me for this situation. If I create sockets, do I need the client to have buttons to initiate the connection? How would I go about using a URL? I just need the server text pane to update every second letting me know that the handheld was able to connect to it, indicating that the battery hasn't died, yet. Later on, I would like to add some other information, but right now, I just need it to send that information. I can mess around with any modifications later on. Thanks for your help!

  • Socket based application - Performance Issues - Suggestions Needed

    Hi All,
    We have an application which basically has been developed using core java. Here is a high level information about the application:
    a) It opens a serversocket which allows clients to connect to it.
    b) For every new client connection, a separate thread is created and this thread deals with requests from clients, processing the data and replying back to clients.
    c) Each socket is polled continuously and sockettimeout is 2 seconds. If there is a timeout, we handle the situation and socket is again read. So basically sockets is read every 2 seconds. If number of timeouts reaches a configurable value, we close the connection and thread is dropped as well.
    d) In production, three instances of this application are running with the help of a cisco load balancer. It is there for last 5 years.
    However there has always been some minor performance isssues and we have sorted them out using different types of garbage collectors, by introducing hardware load balancers, upgrading the code for new Java versions. It is currently running on 1.4.2.
    However there has always been some performance issues and today while googling over internet I came across following on the bea website which says that core java sockets are not as efficients as native API. BEA has implemented its own APIs for weblogic. My queries are:
    a) Are there any better Java Socket/network API (for solairs, I know Java is plateform independenet but there could be lib which also using native libs) which are much more efficient than Core Java.
    b) We are getting the InputStream/OutputStream and creating objects of DataInputStream/DataOutputStream to read the data 'Byte-By-Byte'. Each byte can have different information thats why it is required. Are there any better way of getting info than what we are currently doing.
    c) As I mentioned, we are continously polling the socket for read operation with a timeout value of 2 seconds. What is the better among the following from performance point of view: (1) Frequent read operation with a lesser timeout value or (2) Less Frequent read operations with larger timeout value. (3) Any better idea??
    Please suggest few things or pointers which I could do to improve the performance of the applcations. Many thanks.
    Thanks,Akhil
    From BEA website:-
    "Although the pure-Java implementation of socket reader threads is a reliable and portable method of peer-to-peer communication, it does not provide the best performance for heavy-duty socket usage in a WebLogic Server cluster. With pure-Java socket readers, threads must actively poll all opened sockets to determine if they contain data to read. In other words, socket reader threads are always "busy" polling sockets, even if the sockets have no data to read. This unnecessary overhead can reduce performance."

    My recommendations:
    - Always use a BufferedInputStream and BufferedOutputStream around the socket streams
    - Increase the socket send and receive buffers to at least 32k if you are on a Windows platform where the default is a ridiculous 8k, which hasn't been enough for about 15 years.
    - Your 2-second timeout is far too short. Increase it to at least 10 seconds.
    - Your strategy of counting up to N short timeouts of S seconds each is completely pointless. Change it to one single timeout of N*S seconds. There is nothing to be gained by the complication you have introduced to this.

  • Socket Based Server's Performance?

    Now i am write a prototype of a Server, using Socket/ServerSocket to communicate.
    The problem is that the performance is low:(
    When the Server listens the Client Input Stream i use a loop forever to detect the Input Stream, this cause the usage rate of CPU is so high(80%~95%).
    It is so expensive, and other Application runs Slow.
    So any advise to me?
    3ks.

    Two choices, one using "standard" IO and one using the "nio" packages.
    With standard IO - each connection from a client is spun into its own Thread. Each Thread blocks at the read. There is no "busy wait" loop; the main ServerSocket is blocked waiting for new connections, any existing connections are blocked on reads. When new data comes in, the appropriate Thread wakes up, does whatever it does, and goes back to reading.
    The downside of this is that it doesn't scale to large numbers of simultaneous connections. Too many Threads will choke any machine (esp. when "too many" gets into the 1's or 10's of thousands...) With the "nio" packages, you can have one Thread handle many connections at one, by using select() and looking to see which ones have data ready.
    Sounds like you need to bone up on server design, tho - this is a well-understood problem, and there's lots of writing about it out there. Google (or a good tech bookstore) is your friend!
    Good luck

  • Creating server/client program to send images

    Hi, I'm trying to create a program where the server and client can send pictures to each other. I don't really know where to start. I want to try to work on the most tedious part of the program first.
    A rough image of how it would execute in the following order:
    1.User type in their username
    2.User selects if they are the server or client
    3.User types in IP address/route number (kind of fuzzy on this one)
    4.The window for transferring photo
    Thank you very much.
    (I'm new at programming, but my goal is to try to develop the program with minimum help from my friends as possible.)

    The best thing to do is to get introduced to the API that you will be using. The most difficult part will be establishing a connection to from client to server and sending/receiving data. Look at the Java API here: http://java.sun.com/javase/6/docs/api/ and scroll down the left side to the URLConnection class, which is the one you will use for the communication.
    When using URLConnection, see http://www.javaworld.com/javaworld/jw-03-2001/jw-0323-traps.html to help get around some of the traps in using it.
    Start with two separate programs, one server and one client. Make both programs command line applications, and don't worry about users etc.. to start with. Maybe even use a fixed IP address and Port for the server. Start with sending text back and forth, and when you get that down switch to images. Then worry about the user interface, logging in, selecting images to serve, location to save to, etc...

  • Server Client Program

    I want to write a server program to accept five clients to send integers to the server only and to accept other five clients to receive integers from the server only. I have got a big stick in here. Anyone can give me an idea?

    LackOfInformationException thrown by darkemprorer's original post, process terminated.
    Clarification of requirements required to help you with your problem.

  • Yes, its another chat server/client program

    Im busy writing a chat program and am having a problem figuring out how to show the users that are online. The ChatServer class contains methods for recieving messages, broadcasting messages, accepting new connections etc.
    Im using non-blocking mode and I register all the connections with a Selector. When a new user connects to the server, I add the SocketChannel to a LinkedList which contains all the users that are online.
    My problem is that my ChatServer class runs completly seperatly from any other classes (I presume thats normal?). In other words, I run the ChatServer and once that is running I run the StartGUI class which creates the swing gui and all of that. I then type in the host name etc and connect to the server. So how would I show the users that are online? Even if I can somehow get all the ip addresses then ill figure out how to give 'nicks' and all that from there.
    As I said, I have a line (LinkedList.add(newChannel) which adds the clients to that list which I simply did so that i can display the number of users online. Is there a way I could now manipulate that LinkedList to get all the users and then display them (since it contains a list of all the SocketChannels)? Or would that not be possible?
    If it is possible to get the users from the LinkedList, then the other problem is the fact that the list is created as part of the ChatServer so I cant get to it?
    Another way that I thaught might be possible, is that since I register all the keys with a Selector when a new user is added (this happens in the ChatClient clas), then I might be able to get the users from that but im not sure if thats possible?
          readSelector = Selector.open();
          InetAddress addr = InetAddress.getByName(hostname);
          channel = SocketChannel.open(new InetSocketAddress(addr, PORT));
          channel.configureBlocking(false);
          channel.register(readSelector, SelectionKey.OP_READ, new StringBuffer());Ill add to my explanation if need be, since im very new to this sort of programming. Ill post some more code if need be.
    thanks, R

    Through some more playing around this afternoon ive figured out how im going to solve my problem. It may not be the best way to do it but I think that at least it is going to work.
    Im going to convert the LinkedList to a String and then change that into a ByteBuffer, and use channel.write(ByteBuffer) as if it was any other normal message.
    My logic will be as follows:
    Client: click 'get user list' button --> send String 'get users' to the server using channel.write("get users")
    Server: read the String like any other normal String 'channel.read(ByteBuffer) --> decode the ByteBuffer back into a String --> if the String sais "get users" --> put the LinkedList into a String and then into a ByteBuffer --> send the buffer using channel.write(buffer)
    Client: check the incoming buffer for some or other string (maybe an ip address) that will let it know that it is the list of users and not a normal string. Then use a bit of String manipulation to extract the IP addresses from the String.
    Is this a reasonable way of doing it? Any other ideas?
    Also,...Is it alright to add the linked list to a String and then into a ByteBuffer to send? Since if there are for example 100 users online then it will be quite a big string and therefore there will be a lot going into the buffer and being sent by the server. Are there any potential problems I could run into here with lots of users?
    (lol, its been great talking to myself here ;) , hopefully some of you will have some comments or ideas after the weekend.)
    R

  • Basic Java Program help needed urgently.

    I have posted the instructions to my project assignment on here that is due tomorrow. I have spent an extremely large amount of time trying to get the basics of programming and am having some difficulty off of the bat. Someone who has more experience with this and could walk me through the steps is what I am hoping for. Any Help however will be greatly appreciated. I am putting in a lot of effort, but I am not getting the results I need. Thank you for the consideration of assisting me with my issues. If you have any questions please feel free to ask. I would love to open up a dialogue.
    CIS 120
    Mathematical Operators
    Project-1
    Max possible pts 100
    Write a program “MathOperators” that reads two integers, displays user’s name, sum, product,
    difference, quotients and modulus of the two numbers.
    1. Create a header for your project as follows:
    * Prgrammer: Your Name (1 pt) *
    * Class: CIS 120 (1 pt) *
    * Section: (1 pt) *
    * Instructor: (1 pt) *
    * Program Name: Mathematical Operators (1 pt) *
    * Description: This java program will ask the user to enter two integers and *
    display sum, product, difference, quotients and modulus of the two numbers
    * (5 pts) *
    2. Display a friendly message e.g. Good Morning!! (2 pts)
    3. Explain your program to the user e.g. This java program can add, subtract, multiply,
    divide and calculate remainder of any two integer numbers entered by you. Let’s get
    started…. (5 pts)
    4. Prompt the user- Please enter your first name, store the value entered by user in a
    string variable name. Use input.next() instead of input.nextLine(). (8 pts)
    5. Prompt the user- name, enter first integer number , store the value entered by user in
    an integer variable num1.(5 pts)
    6. Prompt the user- name, enter second integer number , store the value entered by user in
    an integer variable num2.(5 pts)
    7. Display the numbers entered by the user as: name has entered the numbers num1and
    num2.(5 pts)
    8. Calculate sum, product, difference, quotients and modulus of the two numbers. ( 30 pts)
    9. Display sum, product, difference, quotients and modulus of the two numbers. ( 10 pts)
    10. Terminate your program with a friendly message like- Thanks for using my program,
    have a nice day!!(2 pts)

    Nice try. You have not demonstrated that you've at least TRIED to do something. No one is going to do your homework for you. Your "urgency" is yours alone.

Maybe you are looking for

  • VB6 - can't save a project with flash.ocx control - why won't Adobe fix?

    After a full day of research, this seems to be an ongling problem for at least a year now.   VB6 developers who have gone in to do maintenance on their applications that call flash.ocx are finding that they can no longer save their projects because o

  • ITunes thinks I don't live in the US

    Someone sent me a file from iTunes that I couldn't open because at the time I was living in Germany. Now I moved the the US and want to view the file but iTunes continues to give me the error message (in German) that this product is only available in

  • Append to excel file

    Hi all, I have got the example in the LV for exporting table to the excel, The problem i am facing is that i have to append the new data to the same file every time a event occurs. The vi is attached below. Thanks in advance . regards Attachments: Wr

  • EDI Transaction type for MRKO Settlement

    Hi, Please let us know what should be the EDI Transaction type to be used for MRKO Settlement . Thanks in advance, Venkat

  • Alert with non-standard fontSize doesn't resize buttons

    //Okay, if you set these style changes in place: _global.styles.Alert.setStyle("backgroundColor", 0x9BCAE1); _global.styles.Alert.setStyle("fontWeight", "bold"); _global.styles.Alert.setStyle("fontSize", 18); _global.styles.Alert.setStyle("color", 0x