Assign unique id to client of socket server

HI
I am in the process of developing a xml socket server application and have hit on a problem. I have managed to create a server that listens for connections and once a request is recieved creates a new client on a seperate thread with the reference being stored in a vector in the server.
However I want to be able to assign an id to a client when it is created so that I can broadcast messages to specific users.

my apologies my question was poorly stated..
When i meant unique i mean that they will have already been prdefined i.e for example the following users
Name David
UserId *(Unique) 0138868
Name sarah
UserId *(Unique) 4138868
Name rob
UserId *(Unique) 7138868
what i want to be able to is when the users connect they can be refeneced by their Userid so that if rob wants to say something to sarah without david knowing. The problem I have is that I do not know how to provide the userid to the server such that the server can create a new client thread with a specified id.
Hope that makes sense ;>

Similar Messages

  • Can i run UDP  client and UDP  server socket program in the same pc ?

    hi all.
    when i execute my UDP client socket program and UDP server socket program in the same pc ,
    It's will shown the error msg :
    "Address already in use: Cannot bind"
    but if i run UDP client socket program in the remote pc and UDP server socket program run in local pc , it's will success.
    anybody know what's going on ?
    any help will be appreciated !

    bobby92 wrote:
    i have use a specified port for UDP server side , and for client define the server port "DatagramSocket clientSocket= new DatagramSocket(Server_PORT);"Why? The port you provide here is not the target port. It's the local port you listen on. That's only necessary when you want other hosts to connect to you (i.e. when you're acting as a server).
    The server should be using that constructor, the client should not be specifying a port.
    so when i start the udp server code to listen in local pc , then when i start UDP client code in local pc ,i will get the error "Address already in use: Cannot bind"Because your client tries to bind to the same port that the server already bound to.

  • How to get MAC Address for maintaning unique client id at server side?

    Hi All,
    Can somebody tell how can i get MAC id for maintaing Unique client id at server.
    or is there any alternative way to do this?
    Thanks in advance..
    CK

    Usually people just use cookies for that.

  • Writing Java Non-Blocking Socket Server for  Winsock Client

    Hi.
    Im a newbie to Sockets. I need to write a Non-Blocking Socket server (using java.nio) that accepts connection and reads the data sent by WinSock clients, and write them to another winsock client. Its quite intriguing. How do I do that? Is it possible?
    Thanks in advance
    Arun

    Well, in traditional 4.2 BSD sockets, you'd fill up a set of filedescriptors of connections (an array of bits usually), and push that in the read parameter of a call to 'select'. Select then blocks until at least one of the file descriptors become available for reading, or writing if you also made an fd_set full of file descriptors (but you can usually write freely to a socket, so there is not much use for that). Then you start finding out which of these file descriptors have actually become available for reading, and you pass those to a bunch of worker-threads. The advantage is that your set of worker-threads can be quite small, while your number of connections can still be quite large (unless, of course, everyone of your clients start talking all at once, but that is no different from the one-socket-one-thread-model that java.net.* forces upon you).
    In java, the 'select' call is replaced by a call to java.nio.channels.Selector.select(); and then the fishing out of the selected stuff comes from java.nio.channels.Selector.selectedKeys().
    To add a thingy to a selector, use (for example) java.nio.channel.ServerSocketChannel.register(Selector, ops, att);
    whereby the ops parameter is the kind of action you'd like to select this channel for; SelectionKey.OP_READ etc..
    The workerthread bit is also easy to write, but I leave that to you as an exercise.

  • Comunication question for socket server and socket client

    I created a simple socket server and a socket client
    The server receive request from server and send same request back to the client.
    Please see example code as below:
    package socket;
    import java.net.*;
    import java.io.*;
    public class SimpleServer {
    public SimpleServer(int listen_port) {
    this.listen_port = listen_port;
    public static void main(String[] args) {
    SimpleServer server = new SimpleServer(4444);
    server.acceptConnections();
    public void acceptConnections() {
    try {
    ServerSocket server = new ServerSocket(listen_port);
    Socket incomingConnection = null;
    while (true) {
    incomingConnection = server.accept();
    handleConnection(incomingConnection);
    } catch (BindException e) {
    System.out.println("Unable to bind to port " + listen_port);
    } catch (IOException e) {
    System.out.println("Unable to instantiate a ServerSocket on port: " + listen_port);
    public void handleConnection(Socket incomingConnection) {
    try {
    InputStream inputFromSocket = incomingConnection.getInputStream();
    BufferedReader streamReader = new BufferedReader(new InputStreamReader(inputFromSocket));
    PrintWriter streamWriter = new PrintWriter(incomingConnection.getOutputStream());
    StringBuffer sb = new StringBuffer();
    String line = null;
    int i = 0;
    while((line=streamReader.readLine())!=null){
    streamWriter.println(line);
    break;
    streamWriter.close();
    streamReader.close();
    incomingConnection.close();
    } catch (Exception e) {
    protected int listen_port;
    //socket client
    package socket;
    import java.io.*;
    import java.net.*;
    import java.util.Iterator;
    import java.util.List;
    import java.math.*;
    public class Simple {
    public Simple(String host_ip, int host_port) {
    this.host_ip = host_ip;
    this.host_port = host_port;
    public static void main(String[] args) {
    Simple simple = new Simple("192.168.254.134", 4444);
    simple.setUpConnection();
    try {
    String result = simple.getResponse("This is first request");
    String result2 = simple.getResponse("This is second request");
    simple.tearDownConnection();
    catch (Exception e) {
    System.out.println("error");
    e.printStackTrace();
    public void setUpConnection() {
    try {
    // Create new socket object
    Socket client = new Socket(host_ip, host_port);
    socketReader = new BufferedReader(new InputStreamReader(client.
    getInputStream()));
    socketWriter = new PrintWriter(client.getOutputStream());
    } catch (UnknownHostException e) {
    System.out.println(
    "Error setting up socket connection: unknown host at " +
    host_ip + ":" + host_port);
    catch (IOException e) {
    System.out.println("Error setting up socket connection: " + e);
    public String getResponse(String request) {
    StringBuffer fileLines = new StringBuffer();
    try {
    socketWriter.println(request);
    socketWriter.flush();
    String line = null;
    int i = 0;
    int chars = 0;
    int sizeOfBuffer = 100;
    char[] cbuf = new char[sizeOfBuffer];
    while ( (chars = socketReader.read(cbuf)) >= 0) {
    fileLines.append(cbuf, 0, chars);
    } catch (Exception e) {
    e.printStackTrace();
    return fileLines.toString();
    public void tearDownConnection() {
    try {
    socketWriter.close();
    socketReader.close();
    } catch (IOException e) {
    System.out.println("Error tearing down socket connection: " + e);
    protected BufferedReader socketReader;
    protected PrintWriter socketWriter;
    protected String host_ip;
    protected int host_port;
    I send two request at the same time.
    Please see code in main method of Simple class
    String result = simple.getResponse("first");
    String result2 = simple.getResponse("second");
    What I think is the socket server will send the same request back to the client.
    So value of result and result2 should be 'first' and 'second'
    But it always return empty String for result2.
    What's the problem?
    Thanks for your help

    Your code has a couple of problems.
    1) the server doesn't flush its socket, so nothing will actually be sent until the socket is closed.
    2) the client getResponse() reads until end of file, so an attempt to use it a second time will fail
    3) in a real application the server should use threads. See the echo server I posted in http://forum.java.sun.com/thread.jsp?forum=11&thread=526980 reply 3.
    Also, please use the [code]  tags when posting source. The lack of these is probaly why you haven't had any repiles until now.

  • Socket Communication between java client and c++ server

    HI,
    In my project,I want to do the following:
    1.Sending datas from client to server.
    2.Getting the response from server to client.
    I written the client in java.but the server is in c++.
    Is it possible to communicate with the server using java codings itself?
    Im able to send the data from my java client to the server.
    but unable to get back the datas from server to client.
    Can anyone tell me how to do this?
    thanks a lot

    hi
    thanks for ur reply.
    I didnt get any error msg while getting the back the datas.
    Actually i divided my application into two parts.
    My application will act as both server and client.
    server ll get the browser request and send to the client and the client will send that data to the c++ server.
    Im able to do that.and unable to get the data from server.
    Didnt get any error.
    can u tell me how to make an application to act as both client and server.
    I think im wrong in that part.
    thanks a lot

  • Doubt on Multithreading socket server

    Iam implemented a multi threaded socket server,My server is going to get the data from the client thro BufferedInputStream and then send back the same data to the originated client.If single client is running means no problem but if more than a client get connected with the server means data frm the client1 is sended to the client2 while client2 data comes to the client1.Iam using buffered output stream for writing data to the client.Iam declared both bufferedoutput and bufferedinput streams as public......... can anyone give the solution for the problem...its very urgen.... can any one do.......

    class ServerSocketDemo
    Lock lo=new ReentrantLock();
    Condition con=lo.newCondition();
    ServerSocket s;
    Socket socket;
    void runServer()
    new Thread(new timeStampDemo(lo)).start();
    s=new ServerSocket(9098);
    for(;;)
    new Thread(new ThreadParent(s.accept(),lo,con)).start();
    class ThreadParent
    Thread[] t;
    Lock lo;
    Condition con;
    ThreadParent(Socket soc,Lock l,Condition c)
    InputStream,OutputStream are created here using socket....
    lo=l;
    con=c;
    public void run()
    for(int i=0;i<2;i++)
    t=new Thread(new ServerThread(OutputStream,lo,con));
    t[i[.start();
    for(;;)
    using InputStream read the data....
    then acquire the lock and then adding the data to linkedlist...
    after adding the data it wil signal to serverthread....
    class ServerThread implements Runnable
    ServerThread(OutputStream,Lock l,Condition c)
    assign all those to corresponding variables....
    public void run()
    for(;;)
    when ever the parent thread signals
    check the linkedlist...
    if the length of the linked list greater than one means retrive the data and using that OutputStream send to corresponding user....
    else it waits on condition variable
    class timeStampDemo
    timeStampDemo(Lock l)
    assign this lock to corresponding variable...
    public void run()
    for(;;){
    The lock variable should be used at certain stage for some period during that time all the process in the server should waits... after the ending of process it releases the lock then the server continues the function..........
    The problem is iam using lock as globally... By implementing the server in that way means i got the same problem... for multiple client,one client data send to another client and vice versa.....if i am using the lock globally in the Parent thread then i wil pass to the Server Thread means it works normally.... But my specification is to compulsorly use the lock before accepting the connection..........

  • Send data to multiple clients from a server

    My problem statement is this:
    A server is created, say X. Multiple clients are created, say A, B & C. If X sends a message to A it should reach only A and should not go to B or C. Similarly if X sends message to B it should not reach A or C. I made a one to one communication with the following code:
    //Server
    import java.io.*;
    import java.net.*;
    class X
    public static void main(String args[])throws Exception
    ServerSocket ss=new ServerSocket(4321);
    try
    Socket s=ss.accept();
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    DataOutputStream out = new DataOutputStream(s.getOutputStream());
    String str=in.readLine();
    out.writeBytes(str+"\n");
    s.close();
    ss.close();
    catch (IOException e){}
    //Client A
    import java.io.*;
    import java.net.*;
    class A
    public static void main(String args[])throws Exception
    try
    Socket s=new Socket("localhost",4321);
    BufferedReader in=new BufferedReader(new InputStreamReader(s.getInputStream()));
    System.out.println(in.readLine());
    s.close();
    catch(Exception e){}
    }But i dont know how to keep track of each client. Because all the clients sockets are created at the same port, ie. 4321. I think thread will help. But even then i dont know how to identify each client. Somebody please help. Thanks in advance.
    Edited by: sowndar on Dec 5, 2009 1:21 AM

    YoungWinston wrote:
    sowndar wrote:
    Ok. I think i have to attach an unique ID to each client message. So that, with the help of that ID, the server can identify each client. Have i caught ur point?If you don't mind using a port per client, you could do something like a receptionist taking incoming calls (on 4321 only).
    - Hi I'm Client xyz.
    - Hi Client xyz, please call me back on port abcd and I'll put you straight through to our server.
    Since 4321 is an "open line" you might have to have some sort of ID so that Clients know which return messages are meant for them, but messages on the other ports would all be direct Client to Server. Also, the Server is then is charge of port allocation and communication on the "open" port is kept to a minimum.4321 is the socket that the server is listening to. It's not what the actual communication will be carried out over. Run this, then telnet to port 12345 a few times
    public class TestServerSocket {
      public static void main(String[] args) throws Exception {
              ServerSocket server = new ServerSocket(12345);
              while (true) {
                   Socket socket = server.accept();
                   System.err.println(socket.getPort());
    }Notice how each inbound connection is allocated a unique outbound socket.

  • Right way to communicate with a socket server (TCP/IP)

    Hi,
    I used to write data from my J2ME socket client to a J2EE socket server with writeUTF(). In this way I can send (and receive) directly Strings.
    When I need an XML file I ask the server with something like os.writeUTF(GIVE_ME_XML_FILE) and I use an XML parser with this socket InputStream.
    I was wondering if it's the right way to proceed ....?
    How do you guys communicate with a server when you need "to talk" a lot ? Do you use only HTTP requests or (if you are allowed to) do you use Socket with writeUTF ?
    Just to know if I'm completely wrong....and if I gonna have unsolicited issues ...
    Thanks..

    AdrienD wrote:
    When I need an XML file I ask the server with something like os.writeUTF(GIVE_ME_XML_FILE) and I use an XML parser with this socket InputStream.
    I was wondering if it's the right way to proceed ....?No, it is not. Read the writeUTF api docs, and you'll know why!
    How do you guys communicate with a server when you need "to talk" a lot ? Do you use only HTTP requests or (if you are allowed to) do you use Socket with writeUTF ?There is answer to this question. it al depends on what data gets send where, how often, and how large..

  • Multiple clients on socket connection

    Hi!
    I understand that it is possible that multiple clients listen to one server (on the same port) and even write to it (then it should be a multi-threaded server).
    But i would like to refuse connectios, if one client is connected. How can I do that?
    In my case I have a (single threaded) server. Now one clients connects. The server waits to receive data from the client and answers, without ever closing the port. that works.
    Now if I connect with a second client, the openicng of the socket in the second client works fine, although the server does not seem to notice the second client. Communication is not possible between the server and the second client, and the server doesn't answer to the first client anymore, although he receives data from it.
    So, since the server does not seem to notice the second client (does not accept the connection) and I don't get an exception at the second client, what can I do?
    Thank you for your help!
    concerned Code (if you want to take a look at it):
    CLIENT:
    socket = new Socket(hostname, echo_port);
    SERVER:
    try
    ServerSocket waitingsocket = new ServerSocket(echo_port);
    try
         socket= waitingsocket.accept();
         System.out.println("Client connected");
         ReaderThread reader = new ReaderThread( this, socket );
         reader.start();          
    catch (Exception e)
    READER:
    public void run()
         while (true)
              try {
                   int bytesRead = inStream.read(inputBuffer,
                   0, inputBuffer.length);
                   readCallback.tcpUpdate(inputBuffer,bytesRead);
              catch (Exception oops)
                   readCallback.tcpUpdate(null,-1);
              

    Just to make sure this is clear: You can NOT have multiple clients on a given socket connection. You CAN have multiple clients connected to a particular port on a given server, but each client will be communicating with the server through a different of socket.
    The usual approach here is to set up a listening ServerSocket on the desired port, call accept() on it, then process the communication from the returned Socket object. This is usually done by spawning a new thread and allowing it to handle the socket communication, while the ServerSocket loops around to another accept() for the next communication.
    Here's an excellent intro to the concepts (the code is really ugly and poorly implemented, but it does a good job of explaining the overall concept). I used this as a starting point, and now (after a whole lot of development) have a pretty sweet extensible web server class that handles template expansion, etc... (I use this as a quick and dirty UI for some of my apps, instead of requiring the user to install a JSP container):
    http://developer.java.sun.com/developer/technicalArticles/Networking/Webserver/
    - K

  • Related to Network program using Java Client and C server

    I am little bit experience in java technology. I need an urgent help as I have to submit a document related to C server and Java client. But while searching in net i cant get a proper guidance for C server as many errors thrown in sys/socket.h and other new header files. Can any one help me out for giving source code for C Server. so that i can further involve in that document. Please help me out. i am really helpless by the way the C server thrown error. after finishing that C server only i can concentrate on Java client...

    Hai Josah,
    Thanks for your reply.. I have gone through many sockets server program in C but the real proble is the header file they include like
    socket.h and in.h etc.. they also provide these header files but if we compile in turboC they inturn require some other header files. I dont get the full hierarchy of C server program. I found some help in Java programming Archive about C Server and java client. As i am new to C i cant get the full header files for the server.c if i complete taht only i can proceed to java client. If u can redirect me for any good C sites also i can be thankful for u forever..please

  • Stream based socket , server implementation

    Please help me with this simple server and socket problem.
    SERVER_
    package com.supratim;
    import java.io.DataInputStream;
    import java.io.DataOutputStream;
    import java.io.IOException;
    import java.net.ServerSocket;
    import java.net.Socket;
    public class SocketServer {
         private static ServerSocket server;
         public static void main(String[] args) throws IOException {
              server = new ServerSocket(9999);
              new SocketServer().go();
         private void go() throws IOException {
         while(true) {
              Socket socket = server.accept();
              DataInputStream dataInputStream = new DataInputStream(socket.getInputStream());
              DataOutputStream dataOutputStream = new DataOutputStream(socket.getOutputStream());
              byte[] buff=new byte[dataInputStream.available()];
              int i;
              while((i=dataInputStream.read())>0) {
                   dataInputStream.read(buff, 0, buff.length);
              String inputMessage="INPUT MESSAGE OBTAINED : "+new String(buff);
              byte[]outputBuffer = inputMessage.getBytes();
              dataOutputStream.write(outputBuffer);
              dataOutputStream.flush();     
              socket.close();
    CLIENT+
    package com.supratim;
    import java.io.DataInputStream;
    import java.io.DataOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.net.Socket;
    import java.net.UnknownHostException;
    public class SocketClient {
         public static void main(String[] args) throws UnknownHostException, IOException {
              new SocketClient().go();
         private void go() throws UnknownHostException, IOException {
              Socket socket = new Socket("localhost",9999);
              InputStream dataInputStream = socket.getInputStream();
              OutputStream dataOutputStream = socket.getOutputStream();
              String inputMessage="ABCDEFGHIJKLMNOPQRSTWXYZ";
              byte[]outputBuffer = inputMessage.getBytes();
              dataOutputStream.write(outputBuffer);
              dataOutputStream.flush();     
              byte[] buff=new byte[dataInputStream.available()];
              int i;
              while((i=dataInputStream.read())>0) {
                   dataInputStream.read(buff, 0, buff.length);
              System.out.println("RESPONSE : "+new String(buff));
              socket.close();
    }When I try to connect to the SERVER from CLIENT, nothing happens. As soon as I terminate the CLIENT, the following stack trace comes...
           Exception in thread "main" java.net.SocketException: Connection reset
            at java.net.SocketInputStream.read(SocketInputStream.java:168)
            at java.net.SocketInputStream.read(SocketInputStream.java:182)
            at java.io.FilterInputStream.read(FilterInputStream.java:66)
            at com.supratim.SocketServer.go(SocketServer.java:26)
            at com.supratim.SocketServer.main(SocketServer.java:14)Please tell me, am I missing something??
    I dont want to use PrintWriter,BufferedReader,BufferedWriter...

    jverd wrote:
    supratim wrote:
    jverd wrote:
    supratim wrote:
    tjacobs01 wrote:
              while((i=dataInputStream.read())>0) {
                   dataInputStream.read(buff, 0, buff.length);
              }This is your problem. InputStream.read is going to block progressif it is so...how am I suppose to check the end of the stream....what is the way out??I'm not really sure what problem you're having or what you're asking. However, if your problem is that you want your server to be able to accept new connections while it's servicing an earlier conneciton--that is, service multiple requests at once--then, clearly, you need to use multiple threads. At the very least, one for accepting connections and one for servicing the requests that come on those connections.The problem is when the client is connecting to send a message as a byte stream...the message does not reach there..eventually the connection resets... why is that?? which part of the SocketServer is being blocked...and what is its way out??
    Let's say it is used in a single threaded environment..only one client is connecting at a time...Does the client flush()? Does it close() the Socket's OutputStream?
    If you don't flush(), data that you have sent may not be received.
    If you don't close(), the server won't know the client is done sending, so he'll never get the -1.
    (Or, alternative to calling OutputStream.close(), you could call Socket.shutdownOutput(), I think.)
    Edited by: jverd on Jul 12, 2011 10:49 AMplease check the code...flushing...closing are all there...

  • Basic Socket Server Principles

    Hi - new to java, programming a socket server (working-ish) but not sure if the principles I am applying are appropriate.
    Basically, during the course of development I decoupled the socket server application logic from the socket server itself so that I could develop them independently. To that ends I have two abstract classes; Server and Service (posted below).from which I derive concrete subclasses (SampleServer and SampleService). The basic idea is that the server handles connections and initializes a service instance. The service obtains the client socket connection, and proceeds to read/write as needed. When the service stops (for whatever reason, error or by accomplishing a goal), the server is supposed to close connections, and wait again for another client.
    Thing is, I have no idea how efficient it is, or what best practice is. Of most concern is Server.run method (questions commented). Of almost equal concern is SampleService.doService(); In my experience, the client (I've been using a flash movie) seems to rarely recieve the entire stream of numbers.before the socket closes. I'd appreciate comments / criticisms / warnings / alternatives etc..
    Thanks in advance.
    David
    *Server.java
    package davi.fol
    import java.net.ServerSocket;
    import java.net.Socket;
    import java.io.IOException;
    * @author David Foley
    public abstract class Server implements Runnable
        protected Thread _thread = null;
        protected Socket _socket = null;
        protected ServerSocket _server;
        protected Service _service;
        public Server(Service service) throws IOException
            _service = service;
            _server = new ServerSocket(_service.getPort());
         * start the server
        public void start()
            if (_thread == null)
                _thread = new Thread(this, _service.getName());
            _thread.start();
            log("- Server.start()");
         * Stop the server
         * @param status - -1 error state, 0 ok
        public void stop(int status)
            try
                stopService();
            catch (Exception exception)
                // uncomment below to fail silently.
                // exception.printStackTrace();
            finally
                _thread = null;
                log("- SocketServer.stop()");
                System.exit(status);
         * Entry point for determining if a an exception can be recovered from @see Server.recoverable
         * to operate if
         * @param exception
        public void recoverOrDie(Exception exception)
            log("- Server.recoverOrDie()");
            if (!recoverable(exception))
                exception.printStackTrace();
                stop(-1);
         * Override this method to obtain an opportunity
         * to handle an exception if encountered. Default @return false
         * @param exception
         * @return
        public Boolean recoverable(Exception exception)
            return false;
        public void run()
            try
                while (_thread.isAlive()) // is this correct?
                    startService(); //initialize the service, passing _socket to Service.start method
                    while (_service.isRunning())
                         // don't do anything else while _service.isRunning == true
                    stopService();
            catch (Exception e)
                recoverOrDie(e);
         * waits until a client connects
         * @throws java.io.IOException
        private void startService() throws IOException
            _socket = _server.accept();
             _service.start(this, _socket);
            log("- Server.openSocket()");
        private void stopService() throws IOException
            if (_socket != null)
                _socket.close();
                _socket = null;
            log("- Server.closeSocket()");
             _service.stop();
        public void log(String message)
            System.out.println(message);
    }And this is the Service class...
    * Service.java
    * Created on 03-Nov-2007 at 18:15:22
    package davi.fol;
    import java.net.Socket;
    import java.io.IOException;
    * @author David Foley
    abstract public class Service
        protected Server _server;
        protected Socket _client = null;
        protected int _port;
        protected String _name;
        protected Boolean _running = true;
         * Service decouples server logic from service logic by centralizing
         * basic server methods with an instance of server
         * @param port
         * @param name
        public Service(int port, String name)
            _port = port;
            _name = name;
         * @return the port number on which the service is opertaing
        public int getPort()
            return _port;
         * @return the name of the service
        public String getName()
            return _name;
         * default method. Override
        public void stop ()
            _running = false;
         * Called by the server when a client connects, providing the
         * service an opportunity to generate and manage its own
         * client io
         * @param server
         * @param client
         * @throws java.io.IOException
        public void start (Server server, Socket client) throws IOException
            _client = client;
            _server = server;
         * @return whetjer the service is running
       abstract public Boolean isRunning();
         * @param message
        public void log(String message)
            //System.out.println(message);
            if(_server != null)
                _server.log(message);
         * @throws java.io.IOException
        abstract public void doService() throws IOException;
    }An sample service (just writes ints to client socket)
    * SampleService.java
    * Created on 05-Nov-2007 at 14:52:11
    package davi.fol;
    import java.io.OutputStream;
    import java.io.IOException;
    * @author onDevice
    public class SampleService extends Service
        public SampleService(int port)
            super(port, "SampleService");
         * @see Service.start(Server server, Socket client)
         * writes the integers 100 to 0 inclusive to the client socket
        public void doService() throws IOException
            OutputStream out = _client.getOutputStream();
            int count = 100;
            while (count > -1)
                out.write(count);
                count--;
            out.close();
            stop();
    * SampleServer.java
    * Created on 05-Nov-2007 at 14:50:55
    package davi.fol;
    import java.io.IOException;
    // just initializes an instance of SampleServer
    public class SampleServer extends Server
        public SampleServer () throws IOException
            super(new SampleService(3000));
    }Edited by: ondevice on Nov 5, 2007 7:31 AM

    Yeah, I've also used jpcap too...same problem because it wraps around WinPCap dll just like Wireshark/Ethereal. No lucks. I even tried Windump, same deal. It seems like so many of these sniffers are built as a wrapper around WinPCap dll so that might be the limiting factor.
    However, I know this this is doable because I have had lucks using:
    http://www.sstinc.com/winsock.html
    But this product is only limited toward Windows OS. I would like to implement this into java so I can operate my application under windows, linux, unix, and mac.
    Would you have any ideas how
    SSTINC built their Winsock analyzer? I'm sure there has got to be a way to work around this....
    Does anyone know if there is a Unix/Linux socket shim/analyzer out there? I'll have my boss buy it if java can not answer our problem.

  • Firewall: Error sending to the socket, server is not responding.

    Hi all,
    I'm trying to connect AIX machine to NT DB2 Database through JDBC with a firewall. I'm using the standard port 6789 in JDBC Applet Server in NT DB2. But I've gotten the following message:
    COM.ibm.db2.jdbc.DB2Exception: [IBM][JDBC Driver] CLI0614E Error sending to the socket, server is not responding. SQLSTATE=08S01
    The connection chain I'm using for AIX side is:
    jdbc:db2://192.168.3.4:6789/DATABASE
    I've configured the firewal to allow the port 6789 to be used, and also the other port 51544 (it's for remote administration, I think). I've also checked that wires and other stuff is working fine, but stil I cannot connect to the Database.
    I don't know if there's something missing on the firewall configuration. Before, everything was working without the firewall.
    Any help will be apreciated, THanks.
    Rodrigo, SPAIN

    It looks like no port problem is happening, because we freed all the ports just to see if client tried to use some of them without our knowing. But it was still the same.
    We were thinking about routing issues, but we were able to ping from client to server, and ports 6789 and 51544 were open as well. Maybe JDBC Client Driver is looking for an different IP address than 192.168.3.4. We know the firewall doesn't receive any query from JDBC Client, and that's very strange because if you see the routing tables in AIX machine, the default route is the firewall. Of course, there's not any other static defined route for the server (192.168.3.4), so it's supposed that default route is going to be used. But it's not.
    We also restarted client machine from scratch but nothing. Maybe this problem happens because there's something wrong in AIX networking settings.
    Rodrigo

  • GUI Freezes once socket server is started

    Here's my problem and I am stumped. I have an application which starts a
    socket server and waits for clients to connect. Once connected, the
    server queries XML to the client for display.
    My problem is when I start the server my GUI freezes. I have a simple
    GUI with a start and stop button made in JBuilder. Although the server is running fine and the application works (I can connect and query with my client) the GUI freezes and I have to CTRALTDEL to close the app.
    The method below (see after message) is in the main Application.java class and my GUI is being created in the Frame1.java class. The Frame class has a listener for the button press which calls startServer in
    Application. This was developed in JBuilder Personal edition.
    I keep reading about InvokeLater but not sure if this is what I need. I feel like what is happening is the server starts and the app listens for clients and ignores the GUI.
    Any suggestions would be helpful as madness is setting in.
    Thnaks.
    public static void startServer() {
    try{
    int intPort=9999;
    ServerSocket server = new ServerSocket(intPort);
    System.out.println("Server started...waiting for clients.");
    while(true){
    Socket objSocket = server.accept();
    SocketClient client = new SocketClient(objSocket);
    client.start();
    catch(IOException ioe){
    //dump error
    Here is how the server is being started:
    void button1_actionPerformed(ActionEvent e) {
    try{
    startserver.main(); //make call to start the server
    label2.setText("Running");
    catch (Exception ie) {
    System.err.println("Could not listen on port: 9999.");
    System.exit(-1);
    }

    Swing executes all GUI related code (event handling, painting, etc.) in the so-called event dispatching thread. If you call a blocking method like ServerSocket.accept in this thread, it is blocked and unable to perform further gui tasks.
    public class MyServerThread extends Thread
        private ServerSocket serversocket;
        public void run()
            try
                this.sserversocket = new ServerSocket(9999);
                while(!Thread.interrupted())
                    Socket socket = serversocket.accept();
                    new SocketClient(socket).start();
            catch(IOException ex)
                ex.printStacktract();
        public void shutdown()
            if(this.serversocket != null)
                //closing the socket will cause accept() to throw an exception and therefor quit its loop
                try { this.serversocket.close(); } catch(IOException ignored) {}
                this.interrupt();
                this.serversocket = null;
    //in your GUI class
    private MyServerThread serverthread;
    void startserver()
        serverthread = new MyServerThread();
        serverthread.start();
    void stopserver()
        serverthread.shutdown();
        serverthread = null;
    }

Maybe you are looking for

  • How do you stop the flash player when you change pages on a web site

    Hi all; I'm building a website in flash using my limited understanding of action script.  Everything was progressing very well until I found that if I go to one of my example pages of my web site and play the flash video (with audio) and click back t

  • Placing More Than One Photo On A Page

    Can you add in the scrapbook format more than one photo per page? I have a friend who wants me to create a DVD for him with over 500 photos, and the only way I can cheat it is by placing two photos together in Photoshop, then putting the large JPG in

  • Error message: iTunes can't save to hard disk because disk not attached. (but it is)  Does this indicate a real problem?

    iTunes regularly post an error message saying it can't save to the internal hard disk because the disk is not attached, even though the disk seems to be functioning normally.  Do these error messages indicate that there is a real problem with either

  • Decmal data in outline fields

    Fellow Forte' users, I am displaying decimal data in an outline field and want to do so to 4 decimal places. The default in the outline field is 2 decimal places. Setting the scale of the decimal data attribute in the outline field display node init

  • Go_Item Built In Behaviour

    Hello All, In Forms 6i i am trying to push the control to a particular item which is not in canvas and the control goes to the next available item in the block sequence which is available in the sequence but doesnt gives/throws any error. But the sam