Simple socket connections

Hey,
I've been dabbling around with sockets lately, and I attempted to create a simple program that allows the client to send messages to the server. However, messages are not being either sent, or received (or both). I do know that the client IS detected and accepted by the server, and that the server is started properly on socket 9999. Here is the code I'm using:
Client.java:
      public static void main(String [] args){
          Socket client = null;
          DataOutputStream output = null;
          DataInputStream input = null;
          Scanner clientInput = new Scanner(System.in);
          InetAddress address = null;
          try{
           address = InetAddress.getLocalHost();
          System.out.println(address);
          catch(UnknownHostException e){
               System.out.println(e);
          try{
               client = new Socket(address, 9999);
               output = new DataOutputStream(client.getOutputStream());
               input = new DataInputStream(client.getInputStream());
          catch(UnknownHostException e){
               System.out.println("Cant find host");
          catch(IOException e){
               System.out.println("IO Exception");
               System.out.println(e);
     //     System.out.println("checkOne");
          if(client != null && output != null && input != null){
               try{
                    boolean redo = true;
                    while(redo){
                         System.out.print("Send to server: ");
                         String text = clientInput.nextLine();
                         if(!(text.equals("!")))
                              output.writeBytes(text);
                         else
                              redo = false;
                         System.out.println();
               catch(IOException e){
                    System.out.println(e);
          try{
          output.close();
          input.close();
          client.close();
          catch(Exception e){
               System.out.println(e);
Server.java:
     public static void main(String [] args){
          ServerSocket server = null;
          Socket client = null;
          DataInputStream input = null;
          PrintStream output = null;
          String line = "";
          try{
               server = new ServerSocket(9999);
               System.out.println("Server started on socket 9999");
          catch(Exception e){
               System.out.println(e);
          try{
               client = server.accept();
               System.out.println("Client detected");
               input = new DataInputStream(client.getInputStream());
               output = new PrintStream(client.getOutputStream());
               while(true){
                    line = input.readLine();
                    output.println(line);
          catch(Exception e){
               System.out.println(e);
     }Could you please tell me what I did wrong with the above code? Did I forget to close a socket, send data incorrectly, or what?
Thanks,
Chris

Chris.Y wrote:
Client.java:
                         if(!(text.equals("!")))
                              output.writeBytes(text);
                         else
That might need to be something like
                         if(!(text.equals("!"))) {
                              output.writeBytes(text);
                              output.writeBytes("\015\012"); // append CR LF
                         elseto satisfy readLine() in the server.

Similar Messages

  • Problem with socket connection through Java Embedding...

    We are trying to create a simple socket connection to a socket server through BPEL PM using the Java Embedding component.
    BPEL Process : Client makes an asynchronous request. Passes an input variable. The input variable is sent to the Server Program through a socket connection through the Java embedding component.
    Server: We are running a simple Socket Server program from command prompt.
    The code below works fine as long as we do not try to receive a response from the server (Commented Code).
    If we uncomment the code and try to receive a response, it refuses to create an instance for the BPEL Process. And sometimes restarts the BPEL Server.
    Client Code:
    String msg="NONE";
    try{
    org.w3c.dom.Element input = (org.w3c.dom.Element) getVariableData("inputVariable","payload","/client:clientProcessRequest/client:input");
    msg = input.getNodeValue();
    Socket clientsoc=new Socket("ServerIP",1000);
    PrintWriter out1=new PrintWriter(clientsoc.getOutputStream());
    out1.write(msg);
    out1.flush();
    BufferedReader cin1=new BufferedReader(new InputStreamReader(clientsoc.getInputStream()));
    msg=cin1.readLine();
    setVariableData("outputVariable","payload","/client:result",new String(msg));
    clientsoc.close();
    catch(UnknownHostException e)
    System.err.println("Don't know about host: dev.");
    System.exit(1);
    catch (IOException e)
    System.err.println("Couldn't get I/O for "+ "the connection to: dev.");
    System.exit(1);
    }

    Repost

  • Help with an exception when trying to establish a socket connection

    i am trying to make a chat (using an applet for the client).......
    it uses an simple socket connection between the server and clients.....when i connect the client to address 127.0.0.1 or localhost everything works fine, but when i try to connect the client to my DNS name or ip, i get an exception....the exception reads:
    java.security.AccessControlException: access denied (java.net.SocketPermission nextwave.dyndns.org resolve)
    at java.security.AccessControlContext.checkPermission(AccessControlContext.java:270)
    at java.security.AccessController.checkPermission(AccessController.java:401)
    at java.lang.SecurityManager.checkPermission(SecurityManager.java:542)
    at java.lang.SecurityManager.checkConnect(SecurityManager.java:1042)
    at java.net.InetAddress.getAllByName0(InetAddress.java:937)
    at java.net.InetAddress.getAllByName0(InetAddress.java:918)
    at java.net.InetAddress.getAllByName(InetAddress.java:912)
    at java.net.InetAddress.getByName(InetAddress.java:832)
    at java.net.InetSocketAddress.<init>(InetSocketAddress.java:109)
    at java.net.Socket.<init>(Socket.java:119)
    at Client.<init>(Client.java:42)
    at ClientApplet.init(ClientApplet.java:12)
    at sun.applet.AppletPanel.run(AppletPanel.java:347)
    at java.lang.Thread.run(Thread.java:536)
    what is this all about??????
    i'm not that fluent in java, or networking at that, but i'm sure there is something i can do to fix this......
    any help would be greatley appreciated.

    this is why i am not heart-broken that i will be going the other (executable jar) route.......the major deciding factor is the people who will be using this chat will most likley not be able to edit the policy file due to lack of knowledge, and probably won't want to take the time to try.....they would rather download a program, and double-click execute........
    i thank you for taking the time to help me......i have been reading through the posts in this forum, and am seeing it is a good place to get help, so i will be sticking around.....
    mahalo and happy java

  • Establishing a socket connection between a .swf file and a socket-test program (TCP/IP builder - Windows), in AS3.

    I have an issue with a college project I'm working on.
    Using Actionscript 3, I made a simple .swf program, an animated, interactive smiley, that 'reacts' to number inputs in a input-box.
    For the sake of the project, I now need to make the framework for establishing a socket connection with the smiley .swf, and another program.
    This is where I encounter issues. I have very little knowledge of AS3 programming, so I'm not certain how to establish the connection - what's required code-wise for it, that is.
    To test the connection, I'm attempting to use the "TCP/IP builder" program from windows, which lets me set up a server socket. I need to program the .swf file into a client - to recognize it, connect to it, then be able to receive data (so that the data can then be used to have the smiley 'react' to it - like how it does now with the input-box, only 'automatically' as it gets the data rather than by manual input).
    My attempts at coding it are as follows, using a tutorial (linked HERE):
    //SOCKET STUFF GOES HERE
        var socket:XMLSocket;        
        stage.addEventListener(MouseEvent.CLICK, doConnect); 
    // This one connects to local, port 9001, and applies event listeners
        function doConnect(evt:MouseEvent):void 
        stage.removeEventListener(MouseEvent.CLICK, doConnect); 
        socket = new XMLSocket("127.0.0.1", 9001);   
        socket.addEventListener(Event.CONNECT, onConnect); 
        socket.addEventListener(IOErrorEvent.IO_ERROR, onError); 
    // This traces the connection (lets us see it happened, or failed)
        function onConnect(evt:Event):void 
            trace("Connected"); 
            socket.removeEventListener(Event.CONNECT, onConnect); 
            socket.removeEventListener(IOErrorEvent.IO_ERROR, onError); 
            socket.addEventListener(DataEvent.DATA, onDataReceived); 
            socket.addEventListener(Event.CLOSE, onSocketClose);             
            stage.addEventListener(KeyboardEvent.KEY_UP, keyUp); 
        function onError(evt:IOErrorEvent):void 
            trace("Connect failed"); 
            socket.removeEventListener(Event.CONNECT, onConnect); 
            socket.removeEventListener(IOErrorEvent.IO_ERROR, onError); 
            stage.addEventListener(MouseEvent.CLICK, doConnect); 
    // Here, the flash tracks what keyboard button is pressed.
    // If 'q' is pressed, the connection ends.
            function keyUp(evt:KeyboardEvent):void 
            if (evt.keyCode == 81) // the key code for q is 81 
                socket.send("exit"); 
            else 
                socket.send(evt.keyCode); 
    // This one should handle the data we get from the server.
            function onDataReceived(evt:DataEvent):void 
            try { 
                trace("From Server:",  evt.data ); 
            catch (e:Error) { 
                trace('error'); 
        function onSocketClose(evt:Event):void 
            trace("Connection Closed"); 
            stage.removeEventListener(KeyboardEvent.KEY_UP, keyUp); 
            socket.removeEventListener(Event.CLOSE, onSocketClose); 
            socket.removeEventListener(DataEvent.DATA, onDataReceived);
    Trying to connect to the socket gives me either no result (other than a 'connection failed' message when I click the .swf), or the following error:
    Error #2044: Unhandled securityError:. text=Error #2048: Security sandbox violation: file:///C|/Users/Marko/Desktop/Završni/Flash%20documents/Smiley%5FTCP%5FIP%5Fv4.swf cannot load data from 127.0.0.1:9001.
        at Smiley_TCP_IP_v4_fla::MainTimeline/doConnect()[Smiley_TCP_IP_v4_fla.MainTimeline::frame1:12] 

    Tried adding that particular integer code, ended up with either errors ("use of unspecified variable" and "implicit coercion") , or no effect whatsoever (despite tracing it).
    Noticed as well that the earlier socket code had the following for byte reading:
    "sock.bytesAvailable > 0" (reads any positive number)
    ...rather than your new:
    "sock.bytesAvailable != 0" (reads any negative/positive number)
    Any difference as far as stability/avoiding bugs goes?
    So then, I tried something different: Have the program turn the "msg" string variable, into a "sentnumber" number variable. This seemed to work nicely, tracing a NaN for text (expected), or tracing the number of an actual number.
    I also did a few alterations to the input box - it now no longer needs the 'enter' key to do the calculation, it updates the animation after any key release.
    With all this considered and the requirements of the project, I now have a few goals I want to achieve for the client, in the following order of priority:
    1) Have the "sentnumber" number variable be recognized by the inputbox layer, so that it puts it into the input box. So in effect, it goes: Connect -> Send data that is number (NaN's ignored) -> number put into input box -> key press on client makes animation react. I optionally might need a way to limit the number of digits that the animation reacts to (right now it uses 1-3 digit numbers, so if I get sent a huge number, it might cause issues).
    - If the NaN can't be ignored (breaks the math/calculus code or some other crash), I need some way of 'restricting' the data it reads to not include NaN's that might be sent.
    - Or for simplicity, should I just detect the traced "NaN" output, reacting by setting the number variable to be "0" in such cases?
    2) After achieving 1), I'll need to have the process be automatic - not requiring a keyboard presses from the client, but happening instantly once the data is sent during a working connection.
    - Can this be done by copying the huge amounts of math/calculus code from the inputbox layer, into the socket layer, right under where I create the "sentnumber" variable, and modifying it delicately?
    3) The connection still has some usability and user issues - since the connection happens only once, on frame 1, it only connects if I already have a listening server when I run the client, and client can't re-connect if the server socket doesn't restart itself.
    I believe to do this, I need to make the connection happen on demand, rather than once at the start.
    For the project's requirement, I also need to allow client users to define the IP / port it's going to connect to (since the only alternative so far is editing the client in flash pro).
    In other words, I need to make a "Connect" button and two textboxes (for IP and port, respectively), which do the following:
    - On pressing "Connect", the button sets whatever is in the text boxes as the address of the IP and port the socket will connect to, then connects to that address without issues (or with a error message if it can't due to wrong IP/port).
    - The connection needs to work for non-local addresses. Not sure if it can yet.
    - On re-pressing connect, the previous socket is closed, then creates a new socket (with new IP/port, if that was altered)
    It seems like making the button should be as simple as putting the existing socket code under the function of a button, but it also seems like it's going to cause issues similar to the 'looping frames' error.
    4) Optional addition: Have a scrolling textbox like the AIR server has, to track what the connection is doing on-the-fly.
    The end result would be a client that allows user to input IP/Port, connects on button press (optionally tracking/display what the socket is doing via scrollbox), automatically alters the smiley based on what numbers are sent whilst the connection lasts, and on subsequent button presses, makes a new connection after closing off the previous one.
    Dropbox link to new client version:
    https://www.dropbox.com/s/ybaa8zi4i6d7u6a/Smiley_TCP_IP_v7.fla?dl=0
    So, starting from 1), can I, and how can I, get the number variable recognized by "inputbox" layer's code? It keeps giving me 'unrecognized variable' errors.

  • Socket connection timeout

    I have a simple threaded client application to connecting to the server
    which is also threaded. I am using the following code to prevent(reduce)
    connection timeouts, but it doesn't seem like timeout period elapses
    before exception is thrown on the client side. Any ideas? Exception
    occurs way before 10 seconds as specified in the code below.
    InetAddress addr = InetAddress.getByName(this.serverName);          
    SocketAddress sockaddr = new InetSocketAddress(addr,this.port);
    Socket socket = new Socket();
    socket.connect(sockaddr,10000);
    The exception I get on the client side is:
    java.net.ConnectException: Connection refused: connect
    Thanks

    The timeout kicks in if the other end hasn't responded within the period. In this case the other end has refused the connect attempt, probably because nothing is listening on the requested port. This can happen well within the timeout period, as you have experienced.

  • Multiple socket connections with MIDP

    dear experts,
    I have a simple problem and I hope someone can help me to solve it.
    I need to open a socket connection from multiple MIDlets on the same port.
    This error occours when I try to make a socket push registration from the second (or third, or fourth...) midlet (I'm able to connect to the socket correctly from the first midlet that makes a push registration):
    PushProcessor.run Exceptionjava.io.IOException: ServerSocket Open
    java.io.IOException: ServerSocket Open
         at com.sun.midp.io.j2me.serversocket.Socket.open(+39)
         at com.sun.midp.io.j2me.socket.Protocol.openPrim(+127)
         at javax.microedition.io.Connector.openPrim(+121)
         at javax.microedition.io.Connector.open(+15)
         at javax.microedition.io.Connector.open(+6)
         at javax.microedition.io.Connector.open(+5)
         at it.myprj.midp.BasicPushMIDlet$PushProcessor.run(+16)
    I would know if push registry API allows to have multiple connection on the same socket port.
    any help is appreciated!
    giovanni

    in my opinion,
    due to the fact when an app binds one port and a second app tries to bind the same (@same time) there will ever be a exception (from my point of view)!
    an no i think that push registry cant register two apps on same port (eg datagram://5060)
    hope this helps
    chris

  • Simple Socket Client

    I've posted examples of a socket client and server that provide a simple message switch in the past. May people have found these examples too complex and the most recent is Java 5 only. The simple client was lost some time ago, so I'm reposting it in an even simpler form. It uses three threads,
    - the AWT Event Dispatch Thread used by Swing
    - a thread that reads text lines and posts them to the GUI using invokeLater
    - a thread that sends text lines from a queue.
    This code is compatible with:
    - Simple Socket Server
    - Socket Example using Java 5
    //================= SimpleClient.java ==========================================//
    * a Simple swing GUI that can communicate with either the SimpleServer or
    * the servers in the pkwnet package.
    * @author PKWooster
    * @version 1.0 Dec 10,2005
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.net.*;
    import java.io.*;
    import java.util.LinkedList;
    public class SimpleClient {
        private JFrame frame = new JFrame("Simple Client");
        private JTextField userText = new JTextField(40);          // input text
         private JTextArea display = new JTextArea(24,40);          // display window
         private JTextField statusText = new JTextField(40);          // status
         private JPanel outPanel = new JPanel();
         private JScrollPane displayScroll = new JScrollPane(display);
         private JMenuBar menuBar = new JMenuBar();
         private JMenuItem startItem = new JMenuItem("Start");
         private JMenuItem hostItem = new JMenuItem("Host");
         private JMenuItem exitItem = new JMenuItem("Exit");
         private JMenu fileMenu = new JMenu("File");
         private JMenu helpMenu = new JMenu("Help");
         private Container cp;
        private volatile int state = CLOSED;
         private String address="127.0.0.1:5050";
        private static final int CLOSED = 0;
        private static final int OPENING = 1;
        private static final int OPENED = 2;
        private static final int CLOSING = 3;
        private String host;
        private int port;
        private Socket sock;
        private BufferedReader in;
        private BufferedWriter out;
        private Thread recvThread;
        private Thread sendThread;
        private String name;
        private LinkedList sendQueue = new LinkedList();
    * construct the SimpleClient
        SimpleClient(String address) {
            this.address = address;
              startItem.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    mnuStart();
              fileMenu.add(startItem);
              hostItem.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    mnuHost();
              fileMenu.add(hostItem);
              exitItem.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    mnuExit();
              fileMenu.add(exitItem);
              menuBar.add(fileMenu);
              menuBar.add(helpMenu);
              frame.setJMenuBar(menuBar);
            cp = frame.getContentPane();
              display.setEditable(false);
              outPanel.add(new JLabel("Send: "));
              outPanel.add(userText);
              // enter on userText causes transmit
              userText.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent evt) {
                    userTyped(evt);
              cp.setLayout(new BorderLayout());
              cp.add(outPanel,BorderLayout.NORTH);
              cp.add(displayScroll,BorderLayout.CENTER);
              cp.add(statusText,BorderLayout.SOUTH);
              setStatus("Closed");
              frame.addWindowListener(new WindowAdapter() {
                public void windowClosing(WindowEvent evt) {
                    mnuExit();
            frame.pack();
            frame.setVisible(true);
    * user pressed enter in the user text field, we try to send the text
        private void userTyped(ActionEvent evt) {
              String txt = evt.getActionCommand()+"\n";
              userText.setText("");     // don't send it twice
              toDisplay(txt);
              if(state == OPENED) {
                send(txt);
         private void toDisplay(String txt) {
              display.append(txt);
              display.setCaretPosition(display.getDocument().getLength() );
        private void setState(int s) {
            state = s;
            if (SwingUtilities.isEventDispatchThread()) {
                showState();
            } else {
                SwingUtilities.invokeLater(new Runnable() {
                    public void run(){
                        showState();
        private void postReceive(final String msg) {
            if (SwingUtilities.isEventDispatchThread()) {
                toDisplay(msg);
            } else {
                SwingUtilities.invokeLater(new Runnable() {
                    public void run() {
                        toDisplay(msg);
    * start and stop connection
         private void mnuStart() {
            if (state == CLOSED) {
                setState(OPENING);
                connect(address);
            } else {
                close();
    * prompt user for host in form address:port
    * default is 127.0.0.1:5050
         private void mnuHost(){
              String txt = JOptionPane.showInputDialog("Enter host address and port",address+":"+port);
              if (txt != null) {
                address = txt;
         // exit menu
         private void mnuExit() {
              close();     
              System.exit(0);
         private void showState () {
            switch(state) {
                case OPENED:
                    startItem.setText("Stop");
                    setStatus("Connected to "+address);
                    break;
                case CLOSED:
                    startItem.setText("Start");
                    setStatus("Disconnected");
                    break;
                case OPENING:
                    setStatus("Connecting to "+address);
                    startItem.setText("Abort");
                    break;
                case CLOSING:
                    setStatus("Disconnecting from "+address);
                    startItem.setText("Abort");
                    break;
         private void setStatus(String st) {
            statusText.setText(st);
        static public void main(String [] args) {
            String address = "127.0.0.1:5050";
            for(int i = 0; i<args.length; i++) {
                address = args;
    final String hostAddress = address;
    SwingUtilities.invokeLater(new Runnable() {
    public void run() {
    SimpleClient client = new SimpleClient(hostAddress);
    * connect to a remote host
    private void connect(String address) {
    setState(OPENING);
    parseAddress(address);
    sendThread = new Thread(new Runnable() {
    public void run() {
    doConnect();
    if (OPENED == state) {
    doSend();
    sendThread.start();
    private void send(String data) {
    synchronized(sendQueue) {
    sendQueue.add(data);
    sendQueue.notifyAll();
    * the main loop for the send thread
    private void doSend() {
    String msg = null;
    while (OPENED == state && null != (msg = waitToSend())) {
    try {
    out.write(msg);
    out.flush();
    } catch(IOException e) {
    e.printStackTrace();
    setState(CLOSING);
    close();
    System.out.println("Thread="+Thread.currentThread().getName()+" ending");
    * connect to a remote host
    private void doConnect() {
    try {
    sock = new Socket(host, port);
    name = ""+sock.getInetAddress()+":"+sock.getPort();
    Thread.currentThread().setName("Send."+name);
    in = new BufferedReader(new InputStreamReader(sock.getInputStream()));
    out = new BufferedWriter(new OutputStreamWriter(sock.getOutputStream()));
    recvThread = new Thread(new Runnable() {
    public void run() {
    doRecv();
    },"Recv."+name);
    recvThread.start();
    setState(OPENED);
    } catch (IOException e) {
    setState(CLOSED);
    private void parseAddress(String txt) {
    String ps = "";
    int n = txt.indexOf(':');
              if(n == 0) {
                   address = "127.0.0.1";
    ps = txt.substring(1);
              } else if (n < 0) {
                   address = txt;
                   ps = "5050";
              } else {
                   address = txt.substring(0,n);
                   ps = txt.substring(n+1);
    try {
    port = Integer.parseInt(ps);
    } catch(NumberFormatException e) {
    port = 5050;
    * get the connection name
    public String getName(){return name;}
    * the main loop for the receive thread
    private void doRecv() {
    String inbuf;
    while (CLOSED != state) {
    try {
    inbuf = in.readLine();
    } catch(Exception e) {
    System.out.println(e);
    inbuf = null;
    if(inbuf == null) {
    close();
    } else {
    postReceive(inbuf+"\r\n");
    System.out.println("Thread="+Thread.currentThread().getName()+" ending");
    private void close() {
    if(state == OPENED) {
    setState(CLOSING);
    try {
    sock.shutdownOutput();
    } catch(IOException ie) {
    ie.printStackTrace();
    close();
    } else if (state != CLOSED) {
    try {
    if (null != out) {
    out.close();
    if (null != in) {
    in.close();
    if (null != sock) {
    sock.close();
    }catch (Exception e) {
    e.printStackTrace();
    if (sendThread.isAlive()) {
    sendThread.interrupt();
    setState(CLOSED);
    private String waitToSend() {
    String msg = null;
    synchronized(sendQueue) {
    try {
    while (sendQueue.isEmpty()) {
    sendQueue.wait();
    msg = (String)sendQueue.remove();
    } catch (InterruptedException e) {
    e.printStackTrace();
    return msg;

    I've posted examples of a socket client and server that provide a simple message switch in the past. May people have found these examples too complex and the most recent is Java 5 only. The simple client was lost some time ago, so I'm reposting it in an even simpler form. It uses three threads,
    - the AWT Event Dispatch Thread used by Swing
    - a thread that reads text lines and posts them to the GUI using invokeLater
    - a thread that sends text lines from a queue.
    This code is compatible with:
    - Simple Socket Server
    - Socket Example using Java 5
    //================= SimpleClient.java ==========================================//
    * a Simple swing GUI that can communicate with either the SimpleServer or
    * the servers in the pkwnet package.
    * @author PKWooster
    * @version 1.0 Dec 10,2005
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.net.*;
    import java.io.*;
    import java.util.LinkedList;
    public class SimpleClient {
        private JFrame frame = new JFrame("Simple Client");
        private JTextField userText = new JTextField(40);          // input text
         private JTextArea display = new JTextArea(24,40);          // display window
         private JTextField statusText = new JTextField(40);          // status
         private JPanel outPanel = new JPanel();
         private JScrollPane displayScroll = new JScrollPane(display);
         private JMenuBar menuBar = new JMenuBar();
         private JMenuItem startItem = new JMenuItem("Start");
         private JMenuItem hostItem = new JMenuItem("Host");
         private JMenuItem exitItem = new JMenuItem("Exit");
         private JMenu fileMenu = new JMenu("File");
         private JMenu helpMenu = new JMenu("Help");
         private Container cp;
        private volatile int state = CLOSED;
         private String address="127.0.0.1:5050";
        private static final int CLOSED = 0;
        private static final int OPENING = 1;
        private static final int OPENED = 2;
        private static final int CLOSING = 3;
        private String host;
        private int port;
        private Socket sock;
        private BufferedReader in;
        private BufferedWriter out;
        private Thread recvThread;
        private Thread sendThread;
        private String name;
        private LinkedList sendQueue = new LinkedList();
    * construct the SimpleClient
        SimpleClient(String address) {
            this.address = address;
              startItem.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    mnuStart();
              fileMenu.add(startItem);
              hostItem.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    mnuHost();
              fileMenu.add(hostItem);
              exitItem.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    mnuExit();
              fileMenu.add(exitItem);
              menuBar.add(fileMenu);
              menuBar.add(helpMenu);
              frame.setJMenuBar(menuBar);
            cp = frame.getContentPane();
              display.setEditable(false);
              outPanel.add(new JLabel("Send: "));
              outPanel.add(userText);
              // enter on userText causes transmit
              userText.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent evt) {
                    userTyped(evt);
              cp.setLayout(new BorderLayout());
              cp.add(outPanel,BorderLayout.NORTH);
              cp.add(displayScroll,BorderLayout.CENTER);
              cp.add(statusText,BorderLayout.SOUTH);
              setStatus("Closed");
              frame.addWindowListener(new WindowAdapter() {
                public void windowClosing(WindowEvent evt) {
                    mnuExit();
            frame.pack();
            frame.setVisible(true);
    * user pressed enter in the user text field, we try to send the text
        private void userTyped(ActionEvent evt) {
              String txt = evt.getActionCommand()+"\n";
              userText.setText("");     // don't send it twice
              toDisplay(txt);
              if(state == OPENED) {
                send(txt);
         private void toDisplay(String txt) {
              display.append(txt);
              display.setCaretPosition(display.getDocument().getLength() );
        private void setState(int s) {
            state = s;
            if (SwingUtilities.isEventDispatchThread()) {
                showState();
            } else {
                SwingUtilities.invokeLater(new Runnable() {
                    public void run(){
                        showState();
        private void postReceive(final String msg) {
            if (SwingUtilities.isEventDispatchThread()) {
                toDisplay(msg);
            } else {
                SwingUtilities.invokeLater(new Runnable() {
                    public void run() {
                        toDisplay(msg);
    * start and stop connection
         private void mnuStart() {
            if (state == CLOSED) {
                setState(OPENING);
                connect(address);
            } else {
                close();
    * prompt user for host in form address:port
    * default is 127.0.0.1:5050
         private void mnuHost(){
              String txt = JOptionPane.showInputDialog("Enter host address and port",address+":"+port);
              if (txt != null) {
                address = txt;
         // exit menu
         private void mnuExit() {
              close();     
              System.exit(0);
         private void showState () {
            switch(state) {
                case OPENED:
                    startItem.setText("Stop");
                    setStatus("Connected to "+address);
                    break;
                case CLOSED:
                    startItem.setText("Start");
                    setStatus("Disconnected");
                    break;
                case OPENING:
                    setStatus("Connecting to "+address);
                    startItem.setText("Abort");
                    break;
                case CLOSING:
                    setStatus("Disconnecting from "+address);
                    startItem.setText("Abort");
                    break;
         private void setStatus(String st) {
            statusText.setText(st);
        static public void main(String [] args) {
            String address = "127.0.0.1:5050";
            for(int i = 0; i<args.length; i++) {
                address = args;
    final String hostAddress = address;
    SwingUtilities.invokeLater(new Runnable() {
    public void run() {
    SimpleClient client = new SimpleClient(hostAddress);
    * connect to a remote host
    private void connect(String address) {
    setState(OPENING);
    parseAddress(address);
    sendThread = new Thread(new Runnable() {
    public void run() {
    doConnect();
    if (OPENED == state) {
    doSend();
    sendThread.start();
    private void send(String data) {
    synchronized(sendQueue) {
    sendQueue.add(data);
    sendQueue.notifyAll();
    * the main loop for the send thread
    private void doSend() {
    String msg = null;
    while (OPENED == state && null != (msg = waitToSend())) {
    try {
    out.write(msg);
    out.flush();
    } catch(IOException e) {
    e.printStackTrace();
    setState(CLOSING);
    close();
    System.out.println("Thread="+Thread.currentThread().getName()+" ending");
    * connect to a remote host
    private void doConnect() {
    try {
    sock = new Socket(host, port);
    name = ""+sock.getInetAddress()+":"+sock.getPort();
    Thread.currentThread().setName("Send."+name);
    in = new BufferedReader(new InputStreamReader(sock.getInputStream()));
    out = new BufferedWriter(new OutputStreamWriter(sock.getOutputStream()));
    recvThread = new Thread(new Runnable() {
    public void run() {
    doRecv();
    },"Recv."+name);
    recvThread.start();
    setState(OPENED);
    } catch (IOException e) {
    setState(CLOSED);
    private void parseAddress(String txt) {
    String ps = "";
    int n = txt.indexOf(':');
              if(n == 0) {
                   address = "127.0.0.1";
    ps = txt.substring(1);
              } else if (n < 0) {
                   address = txt;
                   ps = "5050";
              } else {
                   address = txt.substring(0,n);
                   ps = txt.substring(n+1);
    try {
    port = Integer.parseInt(ps);
    } catch(NumberFormatException e) {
    port = 5050;
    * get the connection name
    public String getName(){return name;}
    * the main loop for the receive thread
    private void doRecv() {
    String inbuf;
    while (CLOSED != state) {
    try {
    inbuf = in.readLine();
    } catch(Exception e) {
    System.out.println(e);
    inbuf = null;
    if(inbuf == null) {
    close();
    } else {
    postReceive(inbuf+"\r\n");
    System.out.println("Thread="+Thread.currentThread().getName()+" ending");
    private void close() {
    if(state == OPENED) {
    setState(CLOSING);
    try {
    sock.shutdownOutput();
    } catch(IOException ie) {
    ie.printStackTrace();
    close();
    } else if (state != CLOSED) {
    try {
    if (null != out) {
    out.close();
    if (null != in) {
    in.close();
    if (null != sock) {
    sock.close();
    }catch (Exception e) {
    e.printStackTrace();
    if (sendThread.isAlive()) {
    sendThread.interrupt();
    setState(CLOSED);
    private String waitToSend() {
    String msg = null;
    synchronized(sendQueue) {
    try {
    while (sendQueue.isEmpty()) {
    sendQueue.wait();
    msg = (String)sendQueue.remove();
    } catch (InterruptedException e) {
    e.printStackTrace();
    return msg;

  • Please help. Simple Socket Question

    Hi. I am writing the basics for a game. Simple. I have a few classes, 1 of which is for connecting and another in which each user inherits a new copy as they join, it contains all their personal variables.
    By having their socket address, how can I access a specific instance of that file?
    Thanks for any help.

    Hi. I am writing the basics for a game. Simple. I
    have a few classes, 1 of which is for connecting and
    another in which each user inherits a new copy as
    they join, it contains all their personal variables.
    By having their socket address, how can I access a
    specific instance of that file?Specific instance of what file? Sockets connect processes to other processes, not to files.

  • Server/Client Socket Connection

    Hi, I am trying to program a simple server/client socket connection program, the main function is to send and receive objects between them. I somehow went wrong and the connection between them keeps terminating right after establishing connection. Is there anything I can do to resolve this?
    This is gonnna be kinda long post.. sorry. These are the code that starts and ends the socket connection. I'm kinda desperate for this to work.. so thanks in advance.
    appinterface.java:
    //Set up server to receive communications; process connections. 1x.
         public void runServer () {
              try {
                   //Create a ServerSocket
                   server = new ServerSocket(12345, 100);
                   try {
                             waitForSockConnection();     //Wait for a connection.
                             getSockStreams();               //Get input & output streams.
                             establishDbConnection();     //Open up connection to DB.
                   finally {
                             closeSockConnection(); //Close connection.
              //Process problems with I/O
              catch(IOException ioException) {
                   displayMessage("I/O Error: " + ioException);
                   runServer();
         //Wait for connection to arrive, then display connection info
         private void waitForSockConnection() throws IOException {
              displayMessage("Waiting for connection");
              connection = server.accept(); //Allow server to accept connection.
              displayMessage("Connection received from: " + connection.getInetAddress().getHostName());
         //Get streams to send and receive data.
         private void getSockStreams() throws IOException {
              //Set up output streams for objects
              ObjectOutputStream output = new ObjectOutputStream(connection.getOutputStream());
              output.flush(); //Flush output buffer to send header information.
              //Set up input stream for objects.
              ObjectInputStream input = new ObjectInputStream(connection.getInputStream());
              try {
              classHolderServer holderObj = new classHolderServer();
              holderObj = (classHolderServer)input.readObject();
              processSockConnection(holderObj);
              displayMessage("Got I/O Streams");
              //Catch problems reading from client
              catch (ClassNotFoundException classNotFoundException) {
                             displayMessage("Unknown object type received");
         //Process connection with client.
         private void processSockConnection(classHolderServer holderObj) throws IOException {
              //sendMessage("Connection Successful");
                        //True is query, and false is auth.
                        if(holderObj.type1==true)
                             processDbStatement(holderObj.type2, holderObj.sqlquery);
                        else {
                             authCheck(holderObj.userName, holderObj.passWord);
                             if(!authCheck)
                             closeDbConnection();
         //Send messages to client.
         private void sendMessage(String message) {
              // Send message to client
              try {
                   ObjectOutputStream output = new ObjectOutputStream(connection.getOutputStream());
                   output.flush();
                   output.writeObject(message);
                   output.flush();
                   displayMessage("Message Sent:" + message);
              catch (IOException ioException) {
                   displayMessage("\nError Sending Message: " + message);
         //Send object to client
         private void sendObject(Object holderObj) {
                   // Send object to client
                   try {
                        ObjectOutputStream output = new ObjectOutputStream(connection.getOutputStream());
                        output.writeObject(holderObj);
                        output.flush();
                        displayMessage("\nObject sent");
                   //Process problems sending object
                   catch (IOException ioException) {
                        displayMessage("\nError writing object");
         //Close streams and socket.
         private void closeSockConnection() {
                   displayMessage("Terminating connection");
                   try {
                        //output.close();
                        //input.close();
                        connection.close();
                        closeDbConnection();
                        this.userName = null;
                        this.passWord = null;
                        this.receiverId = 0;
                        this.authCheck = false;
                   catch (IOException ioException) {
                        displayMessage("I/O Error: " + ioException);
              }Client:
    private void runClient() {
              //Connect to sever and process messages from server.
              try{
                   connectToServer();
                   getStreams();
                   processConnection();
              //Server closed connection.
              catch(EOFException eofException) {
                   //displayMessage"Client Terminated Connection");
              //Process problems communicating with server.
              catch (IOException ioException) {
                   //displayMessage"Communication Problem");
              finally {
                   closeConnection();
         //Connect to server
         private void connectToServer() throws IOException {
              //displayMessage("Attempting connection\n");
              //Create Socket to make connection to sever.
              client = new Socket(InetAddress.getByName(chatServer), 12345);
              //Display connection information
              //displayMessage("Connected to: " + client.getInetAddress().getHostName());
         //Get streams to send and receive data.
         private void getStreams() throws IOException {
              //Set up output stream for objects.
              ObjectOutputStream output = new ObjectOutputStream(client.getOutputStream());
              output.flush(); //Flush outout buffer to send header information.
              //Set up input stream for objects.
              ObjectInputStream input = new ObjectInputStream(client.getInputStream());
              //displayMessage("\nGot I/O streams\n");
         //Close socket connection.
         private void closeConnection() {
              //displayMessage("\nClosing connection");
              try {
                   ObjectOutputStream output = new ObjectOutputStream(client.getOutputStream());
                   output.close();
                   ObjectInputStream input = new ObjectInputStream(client.getInputStream());
                   input.close();
                   client.close();
                   authCheck=false;
              catch(IOException ioException) {
                   ioException.printStackTrace();
         //Send data to server.
         private void sendObject(classHolderClient queryObj) {
              try {
                   output.writeObject(queryObj);
                   output.flush();
                   //displayMessage("Please wait..");
              //Process problems sending object.
              catch (IOException ioException) {
                   //displayMessage("\nError writing object");
         //Process connection with server.
         private void processConnection() throws IOException {
              try{
                   classHolderClient holderObj = new classHolderClient();
                   holderObj = (classHolderClient)input.readObject();
                   if(holderObj.type2==2) {
                             this.authCheck=holderObj.authCheck;
                             this.userName=holderObj.userName;
                             this.passWord=holderObj.passWord;
              catch(ClassNotFoundException classNotFoundException) {
                   //displayMessage(classNotFoundException);
              }

    private ObjectOutputStream output = new ObjectOutputStream(client.getOutputStream());Like this? But this will cause an error asking me to catch an exception:
    C:\Documents and Settings\Moon\My Documents\Navi Projects\School\OOPJ Project\Prototype\GPS-Lite v2 Alpha Debugger\client.java:41: unreported exception java.io.IOException; must be caught or declared to be thrown
            private ObjectOutputStream output = new ObjectOutputStream(client.getOutputStream());
                                                                                             ^
    C:\Documents and Settings\Moon\My Documents\Navi Projects\School\OOPJ Project\Prototype\GPS-Lite v2 Alpha Debugger\client.java:41: unreported exception java.io.IOException; must be caught or declared to be thrown
            private ObjectOutputStream output = new ObjectOutputStream(client.getOutputStream());
                                                ^
    2 errors

  • Socket connect slow in JDK 1.5?

    We recently began testing our Java Swing application with JDK 1.5, and we noticed that socket.connect()
    calls are taking several seconds to return, when before in 1.4 the calls returned immediately.
    Here is some sample code:
    Socket sock = new Socket();
    InetSocketAddress sockAddr = new InetSocketAddress(inAddress, portNum);
    sock.connect(sockAddr, 2000);
    What could be wrong? I've debugged the code and verified inAddress is an IP address,
    not a hostname.
    -Eric

    Here is the list of enhancements in JDK1.5.
    http://java.sun.com/j2se/1.5.0/docs/guide/net/enhancements-1.5.0.html
    I wonder if any of them are having some effect in the slow connection.
    There are some network properties that you can tweak with. Did you try them?
    Here is the list
    http://java.sun.com/j2se/1.5.0/docs/guide/net/properties.html

  • Is there any way to identify the particular socket connection is closed ?

    Is there any way to identify the particular socket connection is closed or not ?
    Any methods ???
    How can the program knows the connection is lost or some thing ...
    Is the socket throws some excpetions when there is no active connection ???
    namanc

    If you get an IOException when you try to use the socket, the connection was obviously closed.
    The correct way for an application to know if the socket was closed is:
    1) the server sends a message indicating that the socket should be closed
    2) the client closes the socket itself

  • I suppose it is the problem with socket connection,Please help

    Hi,
    I'm trying to build a chat server in Java on Linux OS.I've created basically 2 classes in the client program.The first one shows the login window.When we enter the Login ID & password & click on the ok button,the data is sent to the server for verification.If the login is true,the second class is invoked,which displays the messenger window.This class again access the server
    for collecting the IDs of the online persons.But this statement which reads from the server causes an exception in the program.If we invoke the second class independently(ie not from 1st class) then there is no problem & the required data is read from the server.Can anyone please help me in getting this program right.I'm working on a p4 machine with JDK1.4.
    The Exceptions caused are given below
    java.net.SocketException: Connection reset by peer: Connection reset by peer
    at java.net.SocketInputStream.SocketRead0(Native Method)
    at java.net.SocketInputStream.read(SocketInputStream.java:119)
         at java.io.InputStreamReader$CharsetFiller.readBytes(InputStreanReader.java :339)
         at java.io.InputStreamReader$CharsetFiller.fill(InputStreamReader.java:374)
         at java.io.InputStreamReader.read(InputStreamReader.java:511)
         at java.io.BufferedReader.fill(BufferedReader.java:139)
         at java.io.BufferedReader.readLine(BufferedReader.java:299)
         at java.io.BufferedReader.readLine(BufferedReader.java:362)
         at Login.LoginData(Login.java:330)
         at Login.test(Login.java:155)
         at Login$Buttonhandler.actionPerformed(Login.java:138)
         at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1722)
         at javax.swing.AbstractButton$ForwardActionEvents.actionPerformed(AbstractButton.java:17775)
         at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:4141)
         at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:253)
         at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:261)
         at java.awt.Component.processMouseEvent(Component.java:4906)
         at java.awt.Component.processEvent(component.java:4732)
         at java.awt.Container.processEvent(Container.java:1337)
         at java.awt.component.dispatchEventImpl(Component.java:3476)
         at java.awt.Container.dispatchEventImpl(Container.java:1399)
         at java.awt.Component.dispatchEvent(Component.java:3343)
         at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:3302)
         at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3014)
         at java.awt.LightweightDispatcher.dispatchEvent(Container.java:2967)
         at java.awt.Container.dispatchEventImpl(Container.java:1373)
         at java.awt.window.dispatchEventImpl(Window.java:1459)
         at java.awt.Component.dispatchEvent(Component.java:3343)
         at java.awt.EventQueue.dispatchEvent(EventQueue.java:439)
         at java.awt.EventDispatchThread.pumpOneEvent(EventDispatchThread.java:150)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:136)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:131)
         at java.awt.EventDispatchThread.run(EventDispatchThread.java:99)
         My program looks somewhat like this :
    1st class definition:
    public class Login extends Jframe// Login is the name of the first class;
    Socket connection;
    DataOutputStream outStream;
    BufferedReader inStream;
    Frame is set up here
    public class Buttonhandler implements ActionListener
    public void actionPerformed(ActionEvent e) {
    String comm = e.getActionCommand();
    if(comm.equals("ok")) {
    check=LoginCheck(ID,paswd);
    test();
    public void test() //checks whether the login is true
    if(check)
    new Messenger(ID);// the second class is invoked
    public boolean LoginCheck(String user,String passwd)
    //Enter the Server's IP & port below
    String destination="localhost";
    int port=1234;
    try
    connection=new Socket(destination,port);
    }catch (UnknownHostException ex){
    error("Unknown host");
    catch (IOException ex){
    ex.printStackTrace ();
    error("IO error creating socket ");
    try{
    inStream = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    outStream=new DataOutputStream(connection.getOutputStream());
    }catch (IOException ex){
    error("IO error getting streams");
    ex.printStackTrace();
    System.out.println("connected to "+destination+" at port "+port+".");
    BufferedReader keyboardInput=new BufferedReader(new InputStreamReader(System.in));
    String receive=new String();
    try{
    receive=inStream.readLine();
    }catch(IOException ex){ error("Error reading from server");}
    if(receive.equals("Logintrue"))
    check=true;
    else
    check=false;
    try{
    inStream.close();
    outStream.close();
    connection.close();
    }catch (IOException ex){
    error("IO error closing socket");
    return(check);
    // second class is defined below
    public class Messenger
    Socket connect;
    DataOutputStream outStr;
    BufferedReader inStr;
    public static void main(String args[])
    { Messenger mes = new Messenger(args[0]);}
    Messenger(String strg)
    CreateWindow();
    setupEvents();
    LoginData(strg);
    fram.show();
    void setupEvents()
    fram.addWindowListener(new WindowHandler());
    login.addActionListener(new MenuItemHandler());
    quit.addActionListener(new MenuItemHandler());
    button.addActionListener(new Buttonhandle());
    public void LoginData(String name)
    //Enter the Server's IP & port below
    String dest="localhost";
    int port=1234;
    int r=0;
    String str[]=new String[40];
    try
    connect=new Socket(dest,port);
    }catch (UnknownHostException ex){
    error("Unknown host");
    catch (IOException ex){
    ex.printStackTrace ();
    error("IO error creating socket ");
    try{
    inStr = new BufferedReader(new InputStreamReader(connect.getInputStream()));
    outStr=new DataOutputStream(connect.getOutputStream());
    }catch (IOException ex){
    error("IO error getting streams");
    ex.printStackTrace();
    String codeln=new String("\n");
    try{
    outStr.flush();
    outStr.writeBytes("!@*&!@#$%^");//code for sending logged in users
    outStr.writeBytes(codeln);
    outStr.write(13);
    outStr.flush();
    String check="qkpltx";
    String receive=new String();
    try{
    while((receive=inStr.readLine())!=null) //the statement that causes the exception
    if(receive.equals(check))
    break;
    else
         str[r]=receive;
         r++;
    }catch(IOException ex){ex.printStackTrace();error("Error reading from socket");}
    catch(NullPointerException ex){ex.printStackTrace();}
    } catch (IOException ex){ex.printStackTrace();
    error("Error reading from keyboard or socket ");
    try{
    inStr.close();
    outStr.close();
    connect.close();
    }catch (IOException ex){
    error("IO error closing socket");
    for(int l=0,k=1;l<r;l=l+2,k++)
    if(!(str[l].equals(name)))
    stud[k]=" "+str[l];
    else
    k--;
    public class Buttonhandle implements ActionListener
    public void actionPerformed(ActionEvent e) {
    //chat with the selected user;
    public class MenuItemHandler implements ActionListener
    public void actionPerformed(ActionEvent e)
    String cmd=e.getActionCommand();
    if(cmd.equals("Disconnect"))
    //Disconnect from the server
    else if(cmd.equals("Change User"))
         //Disconnect from the server & call the login window
    else if(cmd.equals("View Connection Details"))
    //show connection details;
    public class WindowHandler extends WindowAdapter
    public void windowClosing(WindowEvent e){
    //Disconnect from server & then exit;
    System.exit(0);}
    I�ll be very thankful if anyone corrects the mistake for me.Please help.

    You're connecting to the server twice. After you've successfully logged in, pass the Socket to the Messenger class.
    public class Messenger {
        Socket connect;
        public static void main(String args[]) {
            Messenger mes = new Messenger(args[0]);
        Messenger(Socket s, String strg) {
            this.connect = s;
            CreateWindow();
            setupEvents();
            LoginData(strg);
            fram.show();
    }

  • Problem with socket connection

    have my gps reciver connected to the usb port - i have a daemon gpsd running which makes data available on tcp port 2947 for querying. when i do telnet, it gives proper data.
    but when i open a socket connection using java, it does not print anything as output. actually telnet asks for an escape charatcer so i am sending "r" initially to the server but still the program does not print anything as output.
    here is my java code -
    import java.io.*;
    import java.net.Socket;
    public class test2
    public static void main(String[] args)
    try
    Socket s = new Socket("localhost",2947);
    PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(
    s.getOutputStream())),true);
    out.println("r");
    BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
    String line;
    while(true)
    line = in.readLine();
    System.out.println(line);
    catch (Exception e)
    or sometimes it even shows error as
    Exception in thread "main" java.net.SocketException: Invalid argument or cannot assign requested address
    at java.net.PlainSocketImpl.socketConnect(Native Method)
    and this is the output which i get on telnet -
    ot@localhost ~]# telnet localhost 2947
    Trying 127.0.0.1...
    Connected to localhost.
    Escape character is '^]'.
    r
    GPSD,R=1
    $GPRMC,000212,V,18000.0000,N,00000.0000,W,0.0000,180.000,101102,,*1A
    $GPGSA,A,1,,,,,,,,,,,,,,,,*32
    $PGRME,400.00,0.00,0.00*7B
    $GPRMC,000213,V,18000.0000,N,00000.0000,W,0.0000,180.000,101102,,*1B
    $GPGSA,A,1,,,,,,,,,,,,,,,,*32
    $PGRME,400.00,0.00,0.00*7B
    $GPRMC,000214,V,18000.0000,N,00000.0000,W,0.0000,180.000,101102,,*1C
    $GPGSA,A,1,,,,,,,,,,,,,,,,*32

    Actually the problem does not seem to be in the code because i tried some basic client server programs (without any gpsd etc in picture) and even they are not working in linux though they work perfectly in windows (on the same machine). In linux it shows exception
    My socket programs dont work in linux it shows error -
    ot@localhost winc]# java parser
    Exception in thread "main" java.net.SocketException: Invalid argument or cannot assign requested address
    at java.net.PlainSocketImpl.socketConnect(Native Method)
    at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:305)
    at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:171)
    at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:158)
    at java.net.Socket.connect(Socket.java:452)
    at java.net.Socket.connect(Socket.java:402)
    at java.net.Socket.<init>(Socket.java:309)
    at java.net.Socket.<init>(Socket.java:124)
    at parser.main(parser.java:10)
    i have removed the firewall settings etc and it still doesnot work in linux
    what could be the cause for this?
    Sowmya

  • Problem with socket connection in midp 2.0

    hello everyone.
    I'm new one in j2me and I am learning socket connection in j2me. I'm using basic socket,datagram example wich is come with sun java wireless toolkit 2.5. for it i wrote small socket server program on c# and tested it example on my pc and its working fine. also socket server from another computer via internet working fine. But when i instal this socket example into my phone on nokia n78 (Also on nokia 5800) it's not working didn't connect to socket server.. On phone I'm using wi-fi internet. Can anybody help me with this problem? I hear it's need to modify manifest file and set appreciate pressions like this
    MIDlet-Permissions: javax.microedition.io.Connector.socket,javax.microedition.io.Connector.file.write,javax.microedition.io.Connector.ssl,javax.microedition.io.Connector.file.read,javax.microedition.io.Connector.http,javax.microedition.io.Connector.https
    is it true?
    can anybody suggest me how can i solve this problem?
    where can I read full information about socket connection specifiecs in j2me?
    Thanks.

    Maybe this can be helpful:
    [http://download-llnw.oracle.com/javame/config/cldc/ref-impl/midp2.0/jsr118/index.html]
    you can check there the Datagram interface anda DatagramConnection interface and learn a little about that.
    If the client example runs fine in the wireless toolkit emulator, it should run the same way in your phone; i suggest to try to catch some exception that maybe is hapenning and display it on a Alert screen, this in the phone.

  • How to make a socket connection timeout infinity in Servlet doPost method.

    I want to redirect my System.out to a file on a remote server (running Apache Web Server and Apache Tomcat). For which I have created a file upload servlet.
    The connection is established only once with the servlet and the System.out is redirected to it. Everything goes fine if i keep sending data every 10 second.
    But it is required that the data can be sent to the servlet even after 1 or 2 days. The connection should remain open. I am getting java.net.SocketTimeoutException: Read timed out Exception as the socket timeout occurs.
    Can anyone guide me how to change the default timeout of the socket connection in my servlet class.
    Following is the coding to establish a connection with the Servlet.
    URL servletURL = new URL(mURL.getProtocol(), mURL.getHost(), port, getFileUploadServletName() );
    URLConnection mCon = servletURL.openConnection();
    mCon.setDoInput(true);
    mCon.setDoOutput(true);
    mCon.setUseCaches(false);
    mCon.setRequestProperty("Content-Type", "multipart/form-data");
    In the Servlet Code I am just trying to read the input from the in that is the input stream.
    public void doPost(HttpServletRequest req, HttpServletResponse res)
    throws ServletException, IOException
    BufferedInputStream in = new BufferedInputStream(req.getInputStream());
    byte [] content = new byte[1024];
    do
    read = in.read(content, 0, content.length);
    if (read > 0)
    out.write(content, 0, read);
    I have redirected the System.out to the required position.
    System.setOut(........);
    Can anyone guide me how to change the default timeout of the socket connection in my servlet class.

    I am aware of the setKeepAlive() method, but this can only used with the sockets. Here i am inside a servlet, have access to HTTPServletRequest and HTTPServletResponse and I don't know how to get access to the underlying sockets as the socket handling will be handled by the tomcat itself. If I am right there will be method in the apache tomcat 6.0.x to set this property. But till now I am not getting it.

Maybe you are looking for