Socket.GetoutputStream on os390 - ASCII

using java.net Socket.getOutputStream - to connect and send to a client that wants ASCII but this method insists on sending EBCDIC if running in USS on an mvs system.. how to force ASCII ??
Thanx in advance

What do you mean, it insists on sending EBCDIC? You are writing to the output stream, aren't you? If your problem is that the data you are sending is in EBCDIC, then just convert it to ASCII before you send it. Like this:// assume you have an array of bytes called ebcdic
// that holds data encoded in EBCDIC.
String s = new String(ebcdic, "CP037");
byte[] ascii = s.toBytes("ASCII");
// now you have the same bytes, translated to ASCII.
// Send them to the socket.

Similar Messages

  • Socket.getOutputStream must precede the socket.getInputStream?!? Why?

    This is server code.......
    import java.io.*;
    import java.net.*;
    import java.util.*;
    public class DateServer extends Thread {
       private ServerSocket dateServer;
       public static void main(String argv[]) throws Exception {
         new DateServer();
       public DateServer() throws Exception {
         dateServer = new ServerSocket(3000);
         System.out.println("Server listening on port 3000.");
         this.start();
       public void run() {
         while(true) {
           try {
            System.out.println("Waiting for connections.");
            Socket client = dateServer.accept();
            System.out.println("Accepted a connection from: "+
    client.getInetAddress());
            Connect c = new Connect(client);
           } catch(Exception e) {}
    class Connect extends Thread {
       private Socket client = null;
       private ObjectInputStream ois = null;
       private ObjectOutputStream oos = null;
       public Connect() {}
       public Connect(Socket clientSocket) {
         client = clientSocket;
         try {
          ois = new ObjectInputStream(client.getInputStream());
          oos = new ObjectOutputStream(client.getOutputStream());
         } catch(Exception e1) {
             try {
                client.close();
             }catch(Exception e) {
               System.out.println(e.getMessage());
             return;
         this.start();
       public void run() {
          try {
             oos.writeObject(new Date());
             oos.flush();
             // close streams and connections
             ois.close();
             oos.close();
             client.close();
          } catch(Exception e) {}
    }This is client code....
    import java.io.*;
    import java.net.*;
    import java.util.*;
    public class DateClient {
       public static void main(String argv[]) {
          ObjectOutputStream oos = null;
          ObjectInputStream ois = null;
          Socket socket = null;
          Date date = null;
          try {
            // open a socket connection
            socket = new Socket("127.0.0.1", 3000);
            // open I/O streams for objects
            oos = new ObjectOutputStream(socket.getOutputStream());
            ois = new ObjectInputStream(socket.getInputStream());
              System.out.println( "BAU!" );
            // read an object from the server
            date = (Date) ois.readObject();
            System.out.print("The date is: " + date);
            oos.close();
            ois.close();
          } catch(Exception e) {
            System.out.println(e.getMessage());
    }OK.
    Those work just fine. Now if you put socket.getInputStream before the socket.getOutputStream then it hangs!
    Any ideea why this happens and why is not documented... I just lost tow hour tring to figure it out why my program just hangs. After I have set the order as In the example above all works....
    If anyone knows why please share your knowledge...
    Hope this will save others a lot of lost time.

    The order matters because the ObjectOutputStream constructor writes a stream header and the ObjectInputStream constructor reads the header.
    If both ends of the conversation do "new ObjectInputStream()" they both forever wait for the other end to write the header. So one end needs to create the output stream first and the input stream second, and the other end in the other order (or do them in different threads.)
    If it isn't documented it should be IMHO. Re-check the javadocs; if it isn't mentioned file a bug report to Sun. There is a bug parade link on http://java.sun.com/ somewhere.

  • About Socket.isClosed or getOutputStream

    Hi !
    I'm working with a client connected with TCP on a server, using a Socket...
    The server is restarted, ... while the client is not reading or writing from/to socket.
    Is this possible after that, on client side, the Socket.isClosed() and the Socket.getOutputStream are working well (no exception throwed) but a SocketException when writing on outputstream ?
    Thanks
    Ludovic

    When you write data to the output stream, it is buffered by the OS, bundled up using the nader algorithim and sent as a packet, then the packet is rejected by the server it is sent to (or times out) then the client knows the server has disconnected. You might have sent a significant amount of data before all this happens, and there is not much you can do except.
    Read from getInputStream() and wait for an expected reply or an IOException. This will let you know of a success or failure.

  • HELP!! When logging into a remote machine I only get ASCII chracters

    Hello,
    When my program logs into the telnet server....ASCII characters
    continuiosly scroll across my screen continiously. What I should be seeing is C:\.Instead I am seeing a continious stream of ASCII characters.Any sugesstions? (Please see the code below)
    Thanks,
    MM
    public class RemoteConnection
    /* Constructor */
    public RemoteConnection(String Host, int TelnetPort)
         try
         {       /* Create a new Socket and call the pipe streams */
              /* This does not output data to the window */
    socket = new Socket(Host, TelnetPort);
    /* This works...I can create a terminal emulator*/
              //socket = new Socket("time.gov", 13);
    new InputPipe(socket.getOutputStream()).start();
              new OutputPipe(socket).start();
         catch(IOException e)
         txtTelnetWindow.setText("");
    txtTelnetWindow.setText("Error Could not connect to host: "+Host);
              return;
    }/* end Constructor */
    * Inner class (to Remote Connection ) which
    * handles the input stream pipe
    public class InputPipe extends Thread
    /* Create objects of type DataInputStream and PrintStream */
    //DataInputStream is;
         PrintStream os;
    BufferedReader BR_is;
    String TheTxt;
    public InputPipe(OutputStream os)
         /* Creates a Input Stream Reader that uses an underlying buffered reader */
    this.BR_is = new BufferedReader(new InputStreamReader(System.in));
         this.os = new PrintStream(os);
    public void run()
    String line;
         try
              while(true)
    line = BR_is.readLine();
    // TheTxt = txtTelnetWindow.getText();
    //txtTelnetWindow.setText(line);
    /* Print one character at a time */
    os.println(line);
    /* Note: DOS only knows "\n", "\r" is Unix */
                   //Used "line seperator" instaed
    //os.print("\r\n");
              //os.print("\n");
    os.flush();
         catch(IOException e)
              throw new RuntimeException("Failed to read or print the line");
    }/* end class input pipe */
    * Inner class (to Remote Connection ) which
    * handles the output stream pipe
    public class OutputPipe extends Thread
         /* Create Stream Objects */
    InputStream in;
         OutputStream ot;
         PrintStream os;
    public OutputPipe(Socket socket)
         try
              this.ot = socket.getOutputStream();
              this.in = socket.getInputStream();
              this.os = new PrintStream(System.out);
         catch(Exception e)
              System.out.println("Oops3");
    public void run()
    /* Create a new String Buffer
    This was the whole formating issue /
    StringBuffer sb = new StringBuffer();
    /* Work on reading text from the counsol */
         int i;
    try
              while(true)
                   /* Reads the next byte of data from the input stream */
    i = in.read();     
    if (i == 255) /* Read in the IAC bytes. Start over after 255th byte*/
                        int i1 = in.read();     
                        int i2 = in.read();
                        Connect(i1,i2);     
                   else
    /* Prints out sun OS, username and login */
    sb.append(""+(char)i);
    //sb.append("\n");
    System.out.print((char)i);
    os.flush();
    txtTelnetWindow.setText(sb.toString());
    catch(Exception e)
         txtTelnetWindow.setText("");
    txtTelnetWindow.setText("You are no longer connected to the host");
    private void Connect(int i1, int i2)
         int i = i1;
         if (i == 253)/* 253 = "DO"*/
         {         /* Write characters to the print Stream */
              i = i2;
         if (i == 1) WriteBytes(i);/* Echo */
              else if (i == 24) WriteBytes(i);/*TTYPE */
              else if (i == 31) WriteBytes(i);/* NAWS */
              else if (i == 35) WriteBytes(i);
              else if (i == 36) WriteBytes(i);
              else if (i == 39) WriteBytes(i);
    private void WriteBytes(int i)
    {                String ReadTxt;
         try
         /* Write the bytes to the output stream from the host machine*/
    ot.write(255); /* IAC*/
              ot.write(252); /* WONT*/
              ot.write(i); /* DO */
         catch (Exception e)
              System.out.println("oops5");
    } /* End output Stream class */
    }/*End Class Remote Connection*/

    I have two suggestions. Firstly, use the [code] tag to format your post. Secondly, log the output to a file and post the first 10 or 20 lines.

  • Can Send ASCII Files Correctly But NOT Binary FIles (TCP)

    In this code right here we are sending in a file and outputting it to the same computer -- we are just trying to test to see if it works. We are breaking the file up into 128 bit packets into byte arrays which we convert to strings to append ACKs, etc.
    When we send and ASCII file it is no problem, and it come out perfectly correct.
    When we send a BINARY file and try view it in wordpad, everything looks the same except sometimes a block (original file) will be a ? (copied file). Yes, it will literally show up as a question mark.
    Our code is below -- any help would be AMAZING.
    // PROGRAMMING ASSIGNMENT #1 (TCPCLIENT.JAVA)
    // Names: Brendan G. Lim, Andrew Tilt, Naoki Kyobashi
    // Class: COMP 4320 - Introduction to Computer Networks
    import java.io.*;
    import java.net.*;
    public class TCPClientString {
    public static int fileSize = 0;
    public static int arrayLength = 0;
    public static byte[] leftOver;
    public static int lengthLeft = 0;
    public static void main(String[] args) throws Exception {
    String fileName = "test.jpg";
    String fileOut = "copy.jpg";
    byte[][] splitArray;
    byte[] sendPacket;
    int ackNum = 1;
                   int fileSizeOut = 0;
    int windowStart = 0;
    int windowEnd = 0;
    int totalAcks = 0;
    //String serverAddress = args[0];
    // final int BUFFER_SIZE = 128;
    // byte[] buffer = new byte[BUFFER_SIZE];
         //Socket socket = new Socket (serverAddress, 6190);
    BufferedInputStream in = new BufferedInputStream(new FileInputStream(fileName));
    // //BufferedOutputStream out = new BufferedOutputStream(socket.getOutputStream());
    BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(fileOut));
    int len = 0;
    splitArray = createFileArray(fileName);
    boolean[] acksRecieved = new boolean[arrayLength];
         for(int i=0; i < arrayLength; i++)
    acksRecieved[i] = false;
         if (arrayLength >= 5)
         windowEnd = 4;
         else
         windowEnd = arrayLength - 1;
    System.out.print(arrayLength);     
    if (arrayLength != 0)
    while(totalAcks != arrayLength)
    for(int l=windowStart; l <= windowEnd && l < arrayLength; l++)
    if (acksRecieved[l] != true)
    sendPacket = getPacket(splitArray, l, l, 128);
    // System.out.println(windowStart);
    //      System.out.println(windowEnd);
    out.write(sendPacket);
                             fileSizeOut += 128;
    acksRecieved[l] = true;
         totalAcks++;
    while (acksRecieved[windowStart] == true && windowStart < arrayLength -1)
         windowStart++;
              if (windowEnd < arrayLength-1)
              windowEnd++;
    if (lengthLeft != 0)
    // System.out.println("did this");
    sendPacket = getPacket(leftOver, ackNum, lengthLeft);
    out.write(sendPacket);
                        fileSizeOut += lengthLeft;
    // System.out.println("\n\nSending File...");
    // while((len = in.read(buffer)) > 0 )
    // out.write(buffer, 0, len);
    in.close();
    out.flush();
    out.close();
    //socket.close();
                   System.out.println("\n \n" fileSize " " +fileSizeOut);
    System.out.println("\n****File Transfered****\n\n");
    public static byte[][] createFileArray(String fileName)throws Exception
    int arraySize = 128;
    FileInputStream fr = new FileInputStream(fileName);
    fileSize = fr.available();
    System.out.println(fileSize);
    arrayLength = fileSize/128;
    int currentPos = 0;
    int bytesRead = 0;
    byte[] msg = new byte[fileSize];
    int counter = 0;
    fr.read(msg);
    byte[][] brokenUp = new byte[arrayLength][arraySize];
    int msgPos = 0;
    if(fileSize >= 128)
    for (int j = 0; j < arrayLength; j++)
    for (int i = 0; i < 128 && msgPos < fileSize; i++)
    brokenUp[j] = msg[msgPos];
    msgPos++;
    if (fileSize%128 != 0)
    lengthLeft = fileSize%128;
    leftOver = new byte [lengthLeft];
    for (int j = 0; j < lengthLeft; j++)
    for (int i = 0; i < 128 && msgPos < fileSize; i++)
    leftOver[i] = msg[msgPos];
    msgPos++;
    return brokenUp;
    public static String getPacket(byte[][] brokenMatrix, int position, int ack, int length)
    byte[] packet = new byte[128];
    String pack;
    String finalPack;
    for (int i = 0; i<128; i++)
    packet[i] = brokenMatrix[position][i];
    pack = new String(packet, 0, 128);
    // finalPack = ack+"**"+"Address1"+"**"+"Address2"+"**";//+pack;
    // System.out.print(pack);
    //packet = pack.getBytes();
    return pack;
    public static String getPacket(byte[] brokenMatrix, int ack, int length)
    byte[] packet = new byte[128];
    String pack;
    String finalPack;
    for (int i = 0; i<length; i++)
    packet[i] = brokenMatrix[i];
    pack = new String(packet, 0, length);
    // //finalPack = ack+"**"+"Address1"+"**"+"Address2"+"**"+pack;
    //packet = pack.getBytes();
    return packet;

    Please use [code][co[/i]de] tags when posting code.
    It's too hard to see unformatted, but from your description I'd suppose you have a call to String#getBytes() somewhere. This method uses the default platform charset, and if they're different, you'd get different results. On the other hand, ASCII chars often have the same encoding (byte), which'd explain why it works with text files.
    You should use the String#getBytes(String) method with a consistant charset, like UTF-8.
    In fact, you shouldn't have to create Strings at all, no, let me rephrase that: you shouldn't pass any Strings around if you'Re sending binary data (nor for the text data, btw.).

  • Initialising a connection to a socket server

    Hi
    I am developing an application that is an on-line temperature & humidity monitoring system. A customer has the
    requirement for data to be sent to his socketServer every hour. The code below works fine as long as the
    serverSocket program is running but crashes on the new Socket instruction if the interconnection is not there.
    The uploadToSocket method is called from a timeline every hour or from a button to test the system.
    I have tried to make sense of the literature on the subject but there seems to be a number of different
    solutions all with examples that are more complex than I need and are difficult to follow. I seem to have to
    run in a different thread and words like tasks and servers are used although one tutorial used listeners. Does
    anyone have a simple solution to this.
       // socket for connection to server
       static private Socket socket = null ;
        // for writing to the server
       static PrintWriter out = null;
        static boolean initSocket(){
            boolean bOK = true ;
            try {
                socket = new Socket(sSocket, Integer.parseInt(sPort));
    //            socket = new Socket("192.168.1.102", 4444);
                out    = new PrintWriter(socket.getOutputStream(),true);
                Ecowand3.lSocket.setText("Socket");  // to say socket is active
            catch (Exception ex) { ex.printStackTrace();
                Ecowand3.lSocket.setText("Socket not found");
                System.err.println("no socket");
                bOK = false ;
           return bOK ;
        static void uploadToSocket(boolean demoMode){
            if (!demoMode){
                boolean bSocketOK = initSocket();
    System.out.println("In upload " + bSocketOK);
                if (bSocketOK){
                try (BufferedReader br = new BufferedReader(new FileReader("socketdata.csv")))
    System.out.println("Trying  upload");
                String sCurrentLine ;
                while ((sCurrentLine = br.readLine()) != null){
                    System.out.println(sCurrentLine + " upload");
                    out.println(sCurrentLine);
                br.close();
                socket.close();
                out.close();
                File f = new File("socketdata.csv");
                boolean bD = f.delete();
    System.out.println("file deleted = " + bD);
            catch(IOException e) { System.err.println("Eco-wand - error with Reading Socket File");}
        }Thanks
    ABG

    Here is one way to do this. The code below neither crashes nor throws an exception for me. Perhaps you could study the code below and apply some of the concepts to your case.
    import java.io.IOException;
    import java.net.ConnectException;
    import java.net.InetSocketAddress;
    import java.nio.*;
    import java.nio.channels.*;
    import java.nio.charset.*;
    import java.text.*;
    import java.util.*;
    import javafx.application.Application;
    import static javafx.application.Application.launch;
    import javafx.scene.Scene;
    import javafx.scene.control.*;
    import javafx.stage.*;
    import java.util.Timer;
    import java.util.logging.*;
    import javafx.event.*;
    import javafx.geometry.Pos;
    import javafx.scene.layout.VBox;
    public class PingApp extends Application {
      private static final DateFormat TIMESTAMP_FORMAT = new SimpleDateFormat("HH:mm:ss.SSS");
      private static final int PORT = 8442;
      private Client client = new Client("localhost", PORT);
      private Server server = new Server("localhost", PORT);
      @Override public void start(Stage stage) {
        server.start();
        Button pingButton = new Button("Ping Now");
        pingButton.setOnAction(new EventHandler<ActionEvent>() {
          @Override public void handle(ActionEvent event) {
            client.pingNow();
        Button startServer = new Button("StartServer");
        startServer.setOnAction(new EventHandler<ActionEvent>() {
          @Override public void handle(ActionEvent event) {
            server.start();
        Button stopServer = new Button("StopServer");
        stopServer.setOnAction(new EventHandler<ActionEvent>() {
          @Override public void handle(ActionEvent event) {
            server.stop();
        VBox layout = new VBox(10);
        layout.setStyle("-fx-background-color: cornsilk; -fx-padding: 10px;");
        layout.setAlignment(Pos.CENTER);
        layout.getChildren().setAll(
          startServer,
          stopServer,
          pingButton
        stage.setScene(new Scene(layout));
        stage.show();
      class Client {
        private final CharsetEncoder encoder = Charset.forName("US-ASCII").newEncoder();
        private final InetSocketAddress address;
        private static final int MILLISECONDS_PER_PING = 5 * 1000;
        public Client(String hostname, int port) {
          address = new InetSocketAddress(hostname, port);
          new Timer("sched-comm").scheduleAtFixedRate(pingTask, 0, MILLISECONDS_PER_PING);
        public void pingNow() {
          Thread thread = new Thread(pingTask, "adhoc-comm");
          thread.setDaemon(true);
          thread.start();
        private final TimerTask pingTask = new TimerTask() {
          private int nCalls = 0;
          @Override public void run() {
            doPing();
          private synchronized void doPing() {
            try (SocketChannel channel = SocketChannel.open()) {
              String msg = createLogMessage("Ping " + nCalls++);
              channel.connect(address);
              System.out.println(createLogMessage("send => '" + msg + "'"));
              channel.write(encoder.encode(CharBuffer.wrap(msg)));
            } catch (ConnectException c) {
              System.out.println(createLogMessage("ping failed => 'Unable to Connect to " + address + "'"));
            } catch (IOException ex) {
              Logger.getLogger(PingApp.class.getName()).log(Level.SEVERE, null, ex);
      class Server {
        private final CharsetDecoder decoder = Charset.forName("US-ASCII").newDecoder();
        private final InetSocketAddress address;
        private Thread thread;
        private boolean shuttingDown = false;
        private final Runnable serverTask = new Runnable() {
          @Override public void run() {
            ServerSocketChannel server;
            try {
              server = ServerSocketChannel.open();
              server.socket().bind(address);
            } catch (IOException ex) {
              Logger.getLogger(PingApp.class.getName()).log(Level.SEVERE, null, ex);
              return;
            ByteBuffer incoming = ByteBuffer.allocateDirect(1024);
            incoming.clear();
            while (true) {
              try (SocketChannel channel = server.accept()) {
                if (Thread.currentThread().isInterrupted()) {
                  return;
                channel.read(incoming);
                incoming.flip();
                CharBuffer charBuffer = decoder.decode(incoming);
                System.out.println(createLogMessage("received => '" + charBuffer.toString() + "'"));
                incoming.compact();
              } catch (ClosedByInterruptException ie) {
                return;
              } catch (IOException ex) {
                Logger.getLogger(PingApp.class.getName()).log(Level.SEVERE, null, ex);
        public Server(String hostname, int port) {
          address = new InetSocketAddress(hostname, port);
        synchronized private void start() {
          System.out.println("Server started");
          if (thread == null) {
            thread = new Thread(serverTask, "server");
            thread.start();
        synchronized private void stop() {
          System.out.println("Server shutting down");
          if (thread != null && !shuttingDown) {
            shuttingDown = true;
            thread.interrupt();
            Thread shutdownWaiter = new Thread(new Runnable() {
              @Override
              public void run() {
                try {
                  thread.join();
                  thread = null;
                  shuttingDown = false;
                } catch (InterruptedException ex) {
                  // no action required.
                System.out.println("Server shutdown");
            }, "shutdown waiter");
            shutdownWaiter.setDaemon(true);
            shutdownWaiter.start();
      private String createLogMessage(String message) {
        return
          TIMESTAMP_FORMAT.format(new Date()) + " " +
          Thread.currentThread().getName() +
          " " +
          message;
      public static void main(String[] args) { launch(args); }
    }

  • Connection refused when trying to getOutputStream from https connection

    Hi all !
    I want to make an https connection with a server to send/get the request/response
    What can be the cause of the following error in the following code testHttps.java?
    java.net.ConnectException: Connection refused: connect
    at java.net.PlainSocketImpl.socketConnect(Native Method)
    at java.net.PlainSocketImpl.doConnect(Unknown Source)
    at java.net.PlainSocketImpl.connectToAddress(Unknown Source)
    at java.net.PlainSocketImpl.connect(Unknown Source)
    at java.net.SocksSocketImpl.connect(Unknown Source)
    at java.net.Socket.connect(Unknown Source)
    at com.sun.net.ssl.internal.ssl.SSLSocketImpl.connect(Unknown Source)
    at com.sun.net.ssl.internal.ssl.BaseSSLSocketImpl.connect(Unknown Source)
    at sun.net.NetworkClient.doConnect(Unknown Source)
    at sun.net.www.http.HttpClient.openServer(Unknown Source)
    at sun.net.www.http.HttpClient.openServer(Unknown Source)
    at sun.net.www.protocol.https.HttpsClient.<init>(Unknown Source)
    at sun.net.www.protocol.https.HttpsClient.New(Unknown Source)
    at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.getNewHttpClient(Unknown Source)
    at sun.net.www.protocol.http.HttpURLConnection.plainConnect(Unknown Source)
    at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(Unknown Source)
    at sun.net.www.protocol.http.HttpURLConnection.getOutputStream(Unknown Source)
    at sun.net.www.protocol.https.HttpsURLConnectionImpl.getOutputStream(Unknown Source)
    at Test.testHttps.main(testHttps.java:46)
    Exception in thread "main" java.net.ConnectException: Connection refused: connect
    at java.net.PlainSocketImpl.socketConnect(Native Method)
    at java.net.PlainSocketImpl.doConnect(Unknown Source)
    at java.net.PlainSocketImpl.connectToAddress(Unknown Source)
    at java.net.PlainSocketImpl.connect(Unknown Source)
    at java.net.SocksSocketImpl.connect(Unknown Source)
    at java.net.Socket.connect(Unknown Source)
    at com.sun.net.ssl.internal.ssl.SSLSocketImpl.connect(Unknown Source)
    at com.sun.net.ssl.internal.ssl.BaseSSLSocketImpl.connect(Unknown Source)
    at sun.net.NetworkClient.doConnect(Unknown Source)
    at sun.net.www.http.HttpClient.openServer(Unknown Source)
    at sun.net.www.http.HttpClient.openServer(Unknown Source)
    at sun.net.www.protocol.https.HttpsClient.<init>(Unknown Source)
    at sun.net.www.protocol.https.HttpsClient.New(Unknown Source)
    at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.getNewHttpClient(Unknown Source)
    at sun.net.www.protocol.http.HttpURLConnection.plainConnect(Unknown Source)
    at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(Unknown Source)
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
    at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(Unknown Source)
    at Test.testHttps.main(testHttps.java:51)
    testHttps.java
    package Test;
    import java.io.;
    import java.net.;
    import javax.net.ssl.*;
    public class testHttps {
    public static void main(String args[]) throws Exception {
    //System.setProperty("java.protocol.handler.pkgs", "com.sun.net.ssl.internal.www.protocol");
    // Create a trust manager that does not validate certificate chains
    TrustManager[] trustAllCerts = new TrustManager[]{
    new X509TrustManager() {
    public java.security.cert.X509Certificate[] getAcceptedIssuers() {
    return null;
    public void checkClientTrusted(
    java.security.cert.X509Certificate[] certs, String authType) {
    public void checkServerTrusted(
    java.security.cert.X509Certificate[] certs, String authType) {
    // Install the all-trusting trust manager
    try {
    SSLContext sc = SSLContext.getInstance("SSL");
    sc.init(null, trustAllCerts, new java.security.SecureRandom());
    HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    } catch (Exception e) {
    System.out.println("Error" e);
    // Now you can access an https URL without having the certificate in the truststore
    try {
    URL url = new URL("https://..............");-->//address of the server given here
    URLConnection conn = url.openConnection();
    HttpsURLConnection urlConn = (HttpsURLConnection) conn;
    urlConn.setDoOutput(true);
    OutputStreamWriter wr = null;
    try{
    wr = new OutputStreamWriter(conn.getOutputStream());
    catch(Exception e){
    e.printStackTrace();
    BufferedReader in = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
    String str;
    while( (str=in.readLine()) != null) {
    System.out.println(str);
    } catch (MalformedURLException e) {
    System.out.println("Error in SLL Connetion" +e);
    HostnameVerifier hv = new HostnameVerifier()
    public boolean verify(String urlHostName, SSLSession session)
    System.out.println("Warning: URL Host: " urlHostName " vs. "
    session.getPeerHost());
    return true;
    want to ignore certificate validation.
    plese help me..
    hi brucechapman, as you suggested me, i posted in Core API- networking forum, now please gimme a solution
    Thanks in advance.

    hi brucechapman,
    ran the NetTest program, got the following exception:
    trigger seeding of SecureRandom
    done seeding SecureRandom
    Exception in thread "main" java.net.ConnectException: Connection refused: connect
         at java.net.PlainSocketImpl.socketConnect(Native Method)
         at java.net.PlainSocketImpl.doConnect(Unknown Source)
         at java.net.PlainSocketImpl.connectToAddress(Unknown Source)
         at java.net.PlainSocketImpl.connect(Unknown Source)
         at java.net.SocksSocketImpl.connect(Unknown Source)
         at java.net.Socket.connect(Unknown Source)
         at com.sun.net.ssl.internal.ssl.SSLSocketImpl.connect(Unknown Source)
         at com.sun.net.ssl.internal.ssl.BaseSSLSocketImpl.connect(Unknown Source)
         at sun.net.NetworkClient.doConnect(Unknown Source)
         at sun.net.www.http.HttpClient.openServer(Unknown Source)
         at sun.net.www.http.HttpClient.openServer(Unknown Source)
         at sun.net.www.protocol.https.HttpsClient.<init>(Unknown Source)
         at sun.net.www.protocol.https.HttpsClient.New(Unknown Source)
         at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.getNewHttpClient(Unknown Source)
         at sun.net.www.protocol.http.HttpURLConnection.plainConnect(Unknown Source)
         at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(Unknown Source)
         at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
         at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(Unknown Source)
         at java.net.URL.openStream(Unknown Source)
         at Test.NetTest.main(NetTest.java:40)
    NetTest.java:40 -- InputStream is = url.openStream(); at this ling throwing exception.
    For the following program, i have added the argument -Djavax.net.ssl.trustStore=cacerts
    i have exported the certificate from IE and added to the keystore.
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.OutputStreamWriter;
    import java.security.Security;
    import javax.net.ssl.SSLSocket;
    import javax.net.ssl.SSLSocketFactory;
    public class Communicator {
    public static void main(String[] args) {
    try {
    int port = 34443;
         String strReq = "xml content ";
    Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
    SSLSocketFactory factory = (SSLSocketFactory) SSLSocketFactory.getDefault();
    SSLSocket socket = (SSLSocket) factory.createSocket("jyoti-win2k8-32", port);
    //Writer out = new OutputStreamWriter(socket.getOutputStream());
    //out.write("GET http://" + "hostname" + "/ HTTP 1.1\r\n");
    // out.write("\r\n");
    //out.write(strReq);
    //out.flush();
    OutputStreamWriter wr = null;
    try{
         wr = new OutputStreamWriter(socket.getOutputStream());
         catch(Exception e){
              e.printStackTrace();
         System.out.println("got output stream");
         try{
         wr.write(strReq);
         //System.out.println("response code : "+conn.getResponseCode());
         System.out.println("written");
         wr.flush();
         catch(IOException e){
              e.printStackTrace();
    InputStreamReader is = new InputStreamReader(socket.getInputStream(),"UTF8") ;
         BufferedReader rd = new BufferedReader(is);
         String line;int count=0;
         System.out.println("rd "+rd);
         while ((line = rd.readLine()) != null) {
              System.out.println("line "+line );
              System.out.println(count++);
              // Process line...
         System.out.println(count);
    rd.close();
    BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    int c;
    while ((c = in.read()) != -1) {
    System.out.write(c);
    //out.close();
    in.close();
    socket.close();
    } catch(IOException ex) {
    ex.printStackTrace();
    Exception :
    javax.net.ssl.SSLException: java.lang.RuntimeException: Unexpected error: java.security.InvalidAlgorithmParameterException: the trustAnchors parameter must be non-empty
         at com.sun.net.ssl.internal.ssl.Alerts.getSSLException(Unknown Source)
         at com.sun.net.ssl.internal.ssl.SSLSocketImpl.fatal(Unknown Source)
         at com.sun.net.ssl.internal.ssl.SSLSocketImpl.fatal(Unknown Source)
         at com.sun.net.ssl.internal.ssl.SSLSocketImpl.handleException(Unknown Source)
         at com.sun.net.ssl.internal.ssl.SSLSocketImpl.handleException(Unknown Source)
         at com.sun.net.ssl.internal.ssl.AppOutputStream.write(Unknown Source)
         at sun.nio.cs.StreamEncoder.writeBytes(Unknown Source)
         at sun.nio.cs.StreamEncoder.implFlushBuffer(Unknown Source)
         at sun.nio.cs.StreamEncoder.implFlush(Unknown Source)
         at sun.nio.cs.StreamEncoder.flush(Unknown Source)
         at java.io.OutputStreamWriter.flush(Unknown Source)
         at Test.Communicator.main(Communicator.java:55)
    Caused by: java.lang.RuntimeException: Unexpected error: java.security.InvalidAlgorithmParameterException: the trustAnchors parameter must be non-empty
         at sun.security.validator.PKIXValidator.<init>(Unknown Source)
         at sun.security.validator.Validator.getInstance(Unknown Source)
         at com.sun.net.ssl.internal.ssl.X509TrustManagerImpl.getValidator(Unknown Source)
         at com.sun.net.ssl.internal.ssl.X509TrustManagerImpl.checkServerTrusted(Unknown Source)
         at com.sun.net.ssl.internal.ssl.X509TrustManagerImpl.checkServerTrusted(Unknown Source)
         at com.sun.net.ssl.internal.ssl.ClientHandshaker.serverCertificate(Unknown Source)
         at com.sun.net.ssl.internal.ssl.ClientHandshaker.processMessage(Unknown Source)
         at com.sun.net.ssl.internal.ssl.Handshaker.processLoop(Unknown Source)
         at com.sun.net.ssl.internal.ssl.Handshaker.process_record(Unknown Source)
         at com.sun.net.ssl.internal.ssl.SSLSocketImpl.readRecord(Unknown Source)
         at com.sun.net.ssl.internal.ssl.SSLSocketImpl.performInitialHandshake(Unknown Source)
         at com.sun.net.ssl.internal.ssl.SSLSocketImpl.writeRecord(Unknown Source)
         ... 7 more
    Caused by: java.security.InvalidAlgorithmParameterException: the trustAnchors parameter must be non-empty
         at java.security.cert.PKIXParameters.setTrustAnchors(Unknown Source)
         at java.security.cert.PKIXParameters.<init>(Unknown Source)
         at java.security.cert.PKIXBuilderParameters.<init>(Unknown Source)
         ... 19 more
    java.net.SocketException: Socket is closed
         at com.sun.net.ssl.internal.ssl.SSLSocketImpl.getInputStream(Unknown Source)
         at Test.Communicator.main(Communicator.java:66)
    please help me and provide me suggestion/solution. how to get rid off this trustanchor paramater exception
    what is it actualy?
    Thanks in advance.

  • Reading from socket inputstream returns -1

    I'm using a socket in order to connect to a chat server. The code is:
    Socket socket;
    InputStreamReader isr;
    OutputStreamWriter osw;
    try {
      socket = new Socket(sHost, iPort);
      isr = new InputStreamReader(socket.getInputStream());
      osw = new OutputStreamWriter(socket.getOutputStream());
      int iCharRead;
      char[] buffer = new char[512];
      while((iCharRead=isr.read(buffer, 0, 512))!=-1) {
          // do something
      System.err.println("Error: InputStream has returned -1.");
      System.err.println("\tsocket.isBound()=" + socket.isBound());
      System.err.println("\tsocket.isClosed()=" + socket.isClosed());
      System.err.println("\tsocket.isConnected()=" + socket.isConnected());
      System.err.println("\tsocket.isInputShutdown()=" + socket.isInputShutdown());
      System.err.println("\tsocket.isOutputShutdown()=" + socket.isOutputShutdown());
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      try {if (isr!=null) isr.close();} catch (Exception ex) {}
      try {if (osw!=null) osw.close();} catch (Exception ex) {}
      try {if (socket!=null) socket.close();} catch (Exception ex) {}
    }Ther server is supposed to be sending data continuously but sometimes, after being connected successfully for a while, the read method returns -1. As you can see in the previous code then I'm checking out some socket information and I get:
    Error: InputStream has returned -1.
         socket.isBound()=true
         socket.isClosed()=false
         socket.isConnected()=true
         socket.isInputShutdown()=false
         socket.isOutputShutdown()=falseThe socket seems to be bounded, it is not closed and isConnected also returns true. Besides, input and output streams are not closed. So, why does the read method return -1? What does it really mean? Is it a problem in the server side, that is overloaded or simply malfunctioning? What can I do in order to keep on reading data from the socket connection? Do I have to close the current socket and reconnect again to the server or is there any other way to recover from this situation?
    Thanks.

    isConnected means was ever connected.
    Check whether isr is closed. If so, the server has disconnected/closed the connection.

  • Problem with socket object writing

    hi,
    I made this little programm , with a class point , a server and a client.
    I try to send via the socket several point object.
    If send differents objects ( with several new point(... )) it works fine , but if i send the same object changing only the properties it doesn't work. Changing are not applicate.
    Here is the code.
    // POINT
    import java.io.Serializable;
    import java.awt.*;
    public class point implements Serializable{
        private int x_;
        private int y_;
        private Color c_;
        public point(int x, int y, Color c) {
           x_=x;
           y_=y;
           c_=c;
        public int get_x() { return x_ ; }
        public int get_y() { return y_ ; }
        public void set_x(int x) { x_=x ; }
        public void set_y(int y) { y_=y ; }
        public Color get_color() { return c_ ; }
    // SERVER
    import java.io.*;
    import java.net.*;
    public class s {
        public s()
            try
                ServerSocket server = new java.net.ServerSocket(80);
                java.net.Socket client  = server.accept();
                ObjectInputStream Istream_ = new ObjectInputStream(client.getInputStream());
                ObjectOutputStream Ostream_ = new ObjectOutputStream(client.getOutputStream());
                for(int i=0;i<4;i++)
                    point p_read = (point)Istream_.readObject();
                    System.out.print("x="+p_read.get_x());
                    System.out.println(" y="+p_read.get_y());
             catch (Exception exception) { exception.printStackTrace(); }
        public static void main(String args[])
         s s_ = new s();
    // CLIENT
    import java.io.*;
    import java.net.*;
    import java.awt.*;
    public class c {
        public c()
            try
                ipJDialog ipjd = new ipJDialog();
                String ip = ipjd.getvalue();
                Socket socket  = new Socket(ip,80);
                System.out.println("connection avec serveur reussi");
                ObjectOutputStream Ostream_ = new ObjectOutputStream(socket.getOutputStream());
                ObjectInputStream Istream_ = new ObjectInputStream(socket.getInputStream());
                point p1 = new point(50,50, new Color(255,0,0));
                Ostream_.writeObject(p1);
                point p2 = new point(22,30, new Color(255,0,0));
                Ostream_.writeObject(p2);
                point p3 = new point(8,7, new Color(255,0,0));
                Ostream_.writeObject(p3);
                point p4 = new point(2,1, new Color(255,0,0));
                Ostream_.writeObject(p4);
             catch (Exception exception) {exception.printStackTrace();}
        public static void main(String args[])
         c c_ = new c();
    // DIALOG TO GET IP FROM INPUTBOX
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    public class ipJDialog extends JDialog implements ActionListener {
        private String ip_;
        private JTextArea jta_;
        private JTextField jtf_;
        private JButton jb1_;
        public ipJDialog()
            this.getContentPane().setLayout(null);
            this.setTitle("Entrez l'IP du serveur");
            this.setSize(220,100);
            this.setModal(true);
            ip_= "localhost";
            jta_ = new JTextArea("IP du serveur :");
            jta_.setBounds(10,5, 90,20);
            jta_.setOpaque(false);
            jta_.setEditable(false);
            getContentPane().add(jta_);
            jtf_ = new JTextField();
            jtf_.setBounds(110,5, 90,20);
            jtf_.requestFocus();
            getContentPane().add(jtf_);
            jb1_ = new JButton("OK");
            jb1_.setBounds(10,30, 90,30);
            jb1_.addActionListener(this);
            getContentPane().add(jb1_);
            this.setVisible(true);
        public String getvalue() { return ip_ ; }
        public void actionPerformed(ActionEvent evt)
            String ChoixOption = evt.getActionCommand();
         if(ChoixOption.equals("OK"))
                ip_=jtf_.getText();
                this.setVisible(false);
    if I replace in client :
             point p1 = new point(50,50, new Color(255,0,0));
                Ostream_.writeObject(p1);
                point p2 = new point(22,30, new Color(255,0,0));
                Ostream_.writeObject(p2);
                point p3 = new point(8,7, new Color(255,0,0));
                Ostream_.writeObject(p3);
                point p4 = new point(2,1, new Color(255,0,0));
                Ostream_.writeObject(p4);
    by :
             point p = new point(50,50, new Color(255,0,0));
                Ostream_.writeObject(p);
                p.set_x(20);
                p.set_x(22);
                Ostream_.writeObject(p);
                p.set_x(55);
                p.set_x(32);
                Ostream_.writeObject(p);
                p.set_x(14);
                p.set_x(88);
                Ostream_.writeObject(p);
    I doesn't work , i receive a point with 50,50 ( the first one ) four times ...If you can explain me me why and what can I do ...
    Thx.

    For ObjectOutputStream, multiple references to a single object are encoded using a reference sharing mechanism so that graphs of objects can be restored to the same shape as when the original was written. State of a object will be recorded so that the ObjectOutputStream doesn't writes the same object to the outputstream when the object was refered by multiple references. So, when you tried to write the same object agains into the ObjectOutputStream, the ObjectOutputStream doesn't write the object, but passed the as a reference to the outputstream... In this case, on the other side, the ObjectInputStream will receive this reference and it will return the reference of this object (which is previous created when this object was passed over on the 1st time). This caused the ObjectInputStream will return a "unchanged" object even your object have changed before you write it agains to the ObjectOutputStream.
    My explaination maybe not that good... hope you can understand... :)

  • Problem with socket and object writing

    Hi,
    I programm this client/server app, the client has a point (graphic ) , the server has a point and when the mouse is moving it moves the point and the new position is send via the socket.
    The probleme is that i don't receive the good thing.
    When i display the coord of the point before sending it's good , but when receiving from the socket the coords are always the same ...
    i don't understand .
    Well , try and tell me ...
    Thx.

    oups, the program can be usefull ...
    import java.applet.*;
    import java.awt.*;
    import java.util.*;
    import java.awt.event.*;
    public class server_JFrame extends javax.swing.JFrame implements MouseListener,MouseMotionListener{
    point p1,p2;
    server s;
    public server_JFrame()
    this.setSize(600,400);
    addMouseListener(this);
    addMouseMotionListener(this);
    p2=new point(50,50,new Color(0,0,255));
    p1=new point(200,200,new Color(255,0,0));
    s = new server(p2,this);
    public void paint(Graphics g)
    super.paint(g);
    g.setColor(p1.get_color());
    g.fillOval(p1.get_x(), p1.get_y(),10,10);
    g.setColor(p2.get_color());
    g.fillOval(p2.get_x(), p2.get_y(),10,10);
    public void mouseClicked(MouseEvent e) { }
    public void mouseEntered(MouseEvent e) {}
    public void mouseExited(MouseEvent e) {}
    public void mousePressed(MouseEvent e) {}
    public void mouseReleased(MouseEvent e) {}
    public void mouseDragged(MouseEvent e) {}
    public void mouseMoved(MouseEvent e)
    p1.set_x(e.getX());
    p1.set_y(e.getY());
    s.write_point(p1);
    repaint();
    public static void main(String args[])
         server_JFrame sjf = new server_JFrame();
    sjf.setDefaultCloseOperation(EXIT_ON_CLOSE);
         sjf.setTitle("server");
    sjf.show();
    import java.io.*;
    import java.net.*;
    import java.util.*;
    import java.awt.*;
    public class server {
    point p_;
    Container c_;
    ObjectInputStream Istream_;
    ObjectOutputStream Ostream_;
    public server(point p,Container c)
    p_=p;
    c_=c;
    try
    ServerSocket server = new java.net.ServerSocket(80);
    System.out.println("attente d'un client");
    java.net.Socket client = server.accept();
    System.out.println("client accept�");
    Istream_ = new ObjectInputStream(client.getInputStream());
    Ostream_ = new ObjectOutputStream(client.getOutputStream());
    ThreadRead tr = new ThreadRead(Istream_,p_,c_);
    catch (Exception exception) { exception.printStackTrace(); }
    public void write_point(point p)
    try
    System.out.print("x="+p.get_x());
    System.out.println(" y="+p.get_y());
    Ostream_.flush();
    Ostream_.writeObject(p);
    Ostream_.flush();
    catch (Exception exception) {exception.printStackTrace();}
    import java.applet.*;
    import java.awt.*;
    import java.util.*;
    import java.awt.event.*;
    public class client_JFrame extends javax.swing.JFrame implements MouseListener,MouseMotionListener{
    point p1,p2;
    client c;
    public client_JFrame()
    this.setSize(600,400);
    addMouseListener(this);
    addMouseMotionListener(this);
    p1=new point(50,50,new Color(0,0,255));
    p2=new point(200,200,new Color(255,0,0));
    c = new client(p2,this);
    public void paint(Graphics g)
    super.paint(g);
    g.setColor(p1.get_color());
    g.fillOval(p1.get_x(), p1.get_y(),10,10);
    g.setColor(p2.get_color());
    g.fillOval(p2.get_x(), p2.get_y(),10,10);
    public void mouseClicked(MouseEvent e) { }
    public void mouseEntered(MouseEvent e) {}
    public void mouseExited(MouseEvent e) {}
    public void mousePressed(MouseEvent e) {}
    public void mouseReleased(MouseEvent e) {}
    public void mouseDragged(MouseEvent e) {}
    public void mouseMoved(MouseEvent e)
    p1.set_x(e.getX());
    p1.set_y(e.getY());
    c.write_point(p1);
    repaint();
    public static void main(String args[])
         client_JFrame cjf = new client_JFrame();
    cjf.setDefaultCloseOperation(EXIT_ON_CLOSE);
         cjf.setTitle("client");
    cjf.show();
    import java.io.*;
    import java.net.*;
    import java.util.*;
    import java.awt.*;
    public class client {
    point p_;
    Container c_;
    ObjectInputStream Istream_;
    ObjectOutputStream Ostream_;
    public client(point p,Container c)
    p_=p;
    c_=c;
    try
    ipJDialog ipjd = new ipJDialog();
    String ip = ipjd.getvalue();
    Socket socket = new Socket(ip,80);
    System.out.println("connection avec serveur reussi");
    Ostream_ = new ObjectOutputStream(socket.getOutputStream());
    Istream_ = new ObjectInputStream(socket.getInputStream());
    ThreadRead tr = new ThreadRead(Istream_,p_,c_);
    catch (Exception exception) {*exception.printStackTrace();*/System.out.println("connection avec serveur echou�");}
    public void write_point(point p)
    try
    System.out.print("x="+p.get_x());
    System.out.println(" y="+p.get_y());
    Ostream_.flush();
    Ostream_.writeObject(p);
    Ostream_.flush();
    catch (Exception exception) {exception.printStackTrace();}
    import java.io.*;
    import java.net.*;
    import java.util.*;
    import java.awt.*;
    public class client {
    point p_;
    Container c_;
    ObjectInputStream Istream_;
    ObjectOutputStream Ostream_;
    public client(point p,Container c)
    p_=p;
    c_=c;
    try
    ipJDialog ipjd = new ipJDialog();
    String ip = ipjd.getvalue();
    Socket socket = new Socket(ip,80);
    System.out.println("connection avec serveur reussi");
    Ostream_ = new ObjectOutputStream(socket.getOutputStream());
    Istream_ = new ObjectInputStream(socket.getInputStream());
    ThreadRead tr = new ThreadRead(Istream_,p_,c_);
    catch (Exception exception) {*exception.printStackTrace();*/System.out.println("connection avec serveur echou�");}
    public void write_point(point p)
    try
    System.out.print("x="+p.get_x());
    System.out.println(" y="+p.get_y());
    Ostream_.flush();
    Ostream_.writeObject(p);
    Ostream_.flush();
    catch (Exception exception) {exception.printStackTrace();}
    import java.io.Serializable;
    import java.awt.*;
    public class point implements Serializable{
    private int x_;
    private int y_;
    private Color c_;
    public point(int x, int y, Color c) {
    x_=x;
    y_=y;
    c_=c;
    public int get_x() { return x_ ; }
    public int get_y() { return y_ ; }
    public void set_x(int x) { x_=x ; }
    public void set_y(int y) { y_=y ; }
    public Color get_color() { return c_ ; }
    }

  • A beginner in socket programming

    Ok I am been stuck on this program for the whole day trying to figure out why I cannot connect to my server computer using sockets and threads.
    I am trying to implement a instant messenger program where each user acts has both client/server. Each client creates a listening socket and all use a common port number, (in this case port 4444).
    If client 1 wants to interact with client 2, client 1 query�s my MySQL database for their status. Now if their status is online, retrieve their current ip address. So far so good. My program does not with no problem.
    Now comes the painful part. Now that client 1 knows client 2 is online and has his/hers ip, the next step is to connect to client 2�s listening socket using their ip and the port number 4444. Now after connecting to that socket, a new chat dialog gui is suppose to open from the client 2�s side. This new chat dialog gui (jframe) is a thread so that if other users wishes to interact with client 2, another new chat dialog thread will appear!
    But in my case nope! Has soon as client 1 tries to establish a connection with client 2, boom. Error, connection refused: connect!!
    Now I been searching through Google trying to understand what this means and so far I found null� now I posted before asking what that means and someone told me it means that I forgot to close the sockets and input, output streams. But how can I close it when I cannot even establish a connection with client 2??
    Things I have tried:
    I tried inputting myself, the actual ip of client 2 and guess what� no luck
    I tried the client 2�s computer name, and same thing!
    I tried to create a whole new main class just so that I can open and close the sockets and input/output stream and nope, no luck at all..
    Now that you have a good understanding of my program. Here comes the code:
    I�l start with the user_window, which is the main menu as you call it: this jframe once opened, is suppose to create a server socket to listen for connections. If a connection is made, load the chatdialog gui thread�
    * user_window.java
    * Created on 10 February 2006, 11:50
    package icomm;
    import java.sql.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.net.*;
    import java.io.*;
    * @author jonathan
    public class user_window extends javax.swing.JFrame implements WindowListener {
    protected String crnt_user;
    protected String crnt_ip;
    protected String dummy = "";
    /** Creates new form user_window */
    public user_window() {
    initComponents();
    listeningSocket();
    addWindowListener( this );
    public user_window(String users_name)
    initComponents();
    addWindowListener( this );
    this.crnt_user = users_name;
    private void exit()
    MySQL_queries offline = new MySQL_queries();
    offline.off_status(crnt_user);
    JOptionPane.showMessageDialog(null, "you are about to close the program " + crnt_user, null, JOptionPane.ERROR_MESSAGE);
    MySQL_queries query = new MySQL_queries();
    query.off_status(crnt_user);
    query.reset_ip(crnt_user);
    System.exit(0);
    public void windowClosing(WindowEvent e)
         exit();
    /** This method is called from within the constructor to
    * initialize the form.
    * WARNING: Do NOT modify this code. The content of this method is
    * always regenerated by the Form Editor.
    // <editor-fold defaultstate="collapsed" desc=" Generated Code ">
    private void initComponents() {
    try {
    Buddie_list =(javax.swing.JTree)java.beans.Beans.instantiate(getClass().getClassLoader(), "icomm.user_window_Buddie_list");
    } catch (ClassNotFoundException e) {
    e.printStackTrace();
    } catch (java.io.IOException e) {
    e.printStackTrace();
    label = new javax.swing.JLabel();
    demo = new javax.swing.JButton();
    jMenuBar1 = new javax.swing.JMenuBar();
    jMenu1 = new javax.swing.JMenu();
    Close = new javax.swing.JMenuItem();
    jMenu2 = new javax.swing.JMenu();
    profile = new javax.swing.JMenuItem();
    jMenu3 = new javax.swing.JMenu();
    getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    getContentPane().add(Buddie_list, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 30, 230, 310));
    getContentPane().add(label, new org.netbeans.lib.awtextra.AbsoluteConstraints(90, 390, -1, -1));
    demo.setText("talk to shienna");
    demo.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    demoActionPerformed(evt);
    getContentPane().add(demo, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 360, -1, -1));
    jMenu1.setText("File");
    jMenu1.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    jMenu1ActionPerformed(evt);
    Close.setLabel("Close");
    Close.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    CloseActionPerformed(evt);
    jMenu1.add(Close);
    jMenuBar1.add(jMenu1);
    jMenu2.setText("Option");
    profile.setText("Edit Profile");
    profile.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    profileActionPerformed(evt);
    jMenu2.add(profile);
    jMenuBar1.add(jMenu2);
    jMenu3.setText("Help");
    jMenuBar1.add(jMenu3);
    setJMenuBar(jMenuBar1);
    pack();
    // </editor-fold>
    private void demoActionPerformed(java.awt.event.ActionEvent evt) {                                    
    // TODO add your handling code here:
    ChatDialog_c chatting = new ChatDialog_c(crnt_user, dummy);
    chatting.setTitle("I-comm");
    chatting.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    chatting.setSize(360, 500);
    chatting.getSize();
    chatting.setLocation(420,200);
    chatting.setVisible(true);
    private void CloseActionPerformed(java.awt.event.ActionEvent evt) {                                     
    // TODO add your handling code here:
    private void demo1ActionPerformed(java.awt.event.ActionEvent evt) {                                     
    // TODO add your handling code here:
    private void show_chat_window()
    ChatDialog chat_gui = new ChatDialog();
    chat_gui.setTitle("chat");
    chat_gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    chat_gui.setSize(366, 480);
    chat_gui.getSize();
    chat_gui.setLocation(420,200);
    chat_gui.setVisible(true);// TODO add your handling code here:
    private void log_offActionPerformed(java.awt.event.ActionEvent evt) {                                       
    private void locate_ip()
    try
    InetAddress a;
    a = InetAddress.getLocalHost(); //get ip addrees
    this.crnt_ip = a.getHostAddress(); //then store it in this variable
    catch(UnknownHostException e)
    JOptionPane.showMessageDialog(null, "Error, cant detect localhost", null, JOptionPane.ERROR_MESSAGE);
    public void windowActivated(WindowEvent e) {}
         public void windowClosed(WindowEvent e) {}
         public void windowDeactivated(WindowEvent e) {}
         public void windowDeiconified(WindowEvent e) {}
         public void windowIconified(WindowEvent e) {}
         public void windowOpened(WindowEvent e)
    locate_ip();
    MySQL_queries new_ip = new MySQL_queries();
    new_ip.update_ip(crnt_user, crnt_ip);
    JOptionPane.showMessageDialog(null,"hello " + crnt_user + " your ip is" + crnt_ip, null, JOptionPane.ERROR_MESSAGE);
    private void listeningSocket()
    ServerSocket serverSocket = null;
    boolean listening = true;
    try
    //listen in port 4444;
    serverSocket = new ServerSocket(4444);
    catch(IOException x)
    JOptionPane.showMessageDialog(null, "cannot listen to port 4444", null, JOptionPane.ERROR_MESSAGE);
    while(listening)
    try
    ChatDialog chat = new ChatDialog(serverSocket.accept());
    catch(IOException x)
    JOptionPane.showMessageDialog(null, "could not open chat window", null, JOptionPane.ERROR_MESSAGE);
    private void jMenu1ActionPerformed(java.awt.event.ActionEvent evt) {                                      
    // TODO add your handling code here:
    private void profileActionPerformed(java.awt.event.ActionEvent evt) {                                       
    // TODO add your handling code here:
    * @param args the command line arguments
    public static void main(String args[]) {
    java.awt.EventQueue.invokeLater(new Runnable() {
    public void run() {
    new user_window().setVisible(true);
    Now for the chatdialog class: I forgot to mention that I have two versions of this class. One that is a thread and the other makes a connection to a thread, hope that makes sence�
    package icomm;
    import java.net.*;
    import java.io.*;
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    public class ChatDialog_c extends javax.swing.JFrame implements WindowListener {
        protected String messege;
        private Socket socket = null;
        protected String ip2;
        private PrintWriter out = null;
        private BufferedReader in = null;
        private String user_name;
        private String status;
        /** Creates new form ChatDialog_c */
        public ChatDialog_c()
            initComponents();
            addWindowListener( this );
         public ChatDialog_c(String ip1)
            initComponents();
            addWindowListener( this );
            this.ip2 = ip1;
            //OptionPane.showMessageDialog(null, "error in closing sockdswdset " + ip2, null, JOptionPane.ERROR_MESSAGE);
         public ChatDialog_c(String user, String status)
            initComponents();
            addWindowListener( this );
            this.user_name = user;
        public void windowClosing(WindowEvent e)
            public void windowActivated(WindowEvent e) {}
         public void windowClosed(WindowEvent e) {
                try
                    in.close();
                    out.close();
                    socket.close();
                catch(IOException x)
                    x.printStackTrace();
                    JOptionPane.showMessageDialog(null, "error in closing socket " + x.getMessage() + ip2, null, JOptionPane.ERROR_MESSAGE);
         public void windowDeactivated(WindowEvent e) {}
         public void windowDeiconified(WindowEvent e) {}
         public void windowIconified(WindowEvent e) {}
          public void windowOpened(WindowEvent e)
              MySQL_queries get_ip = new MySQL_queries();
              this.ip2 = get_ip.find_client(user_name);
               JOptionPane.showMessageDialog(null, user_name + ip2, null, JOptionPane.ERROR_MESSAGE);
                //create socket connection
                try
                    socket = new Socket ("Shienna", 4444);
                    out = new PrintWriter(socket.getOutputStream(), true);
                    in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                catch(UnknownHostException x)
                    x.printStackTrace();
                    JOptionPane.showMessageDialog(null, "unknown  " + x.getMessage() + ip2, null, JOptionPane.ERROR_MESSAGE);
                catch(IOException x)
                    x.printStackTrace();
                    JOptionPane.showMessageDialog(null, "2 " + x.getMessage(), null, JOptionPane.ERROR_MESSAGE);
                 try
                    in.close();
                    out.close();
                    socket.close();
                catch(IOException x)
                    x.printStackTrace();
                    JOptionPane.showMessageDialog(null, "error in closing socket " + x.getMessage() + ip2, null, JOptionPane.ERROR_MESSAGE);
                while(true)
                    try
                        String line = in.readLine();
                        convo_txt.append(line);
                    catch(IOException x)
                        x.printStackTrace();
                        JOptionPane.showMessageDialog(null, "3 " + x.getMessage(), null, JOptionPane.ERROR_MESSAGE);
        /** This method is called from within the constructor to
         * initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is
         * always regenerated by the Form Editor.
        // <editor-fold defaultstate="collapsed" desc=" Generated Code ">                         
        private void initComponents() {
            jScrollPane1 = new javax.swing.JScrollPane();
            convo_txt = new javax.swing.JTextArea();
            jScrollPane2 = new javax.swing.JScrollPane();
            txt_messege = new javax.swing.JTextArea();
            send = new javax.swing.JButton();
            jMenuBar1 = new javax.swing.JMenuBar();
            jMenu1 = new javax.swing.JMenu();
            jMenu2 = new javax.swing.JMenu();
            getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
            jScrollPane1.setViewportView(convo_txt);
            getContentPane().add(jScrollPane1, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 20, 220, 280));
            txt_messege.setLineWrap(true);
            jScrollPane2.setViewportView(txt_messege);
            getContentPane().add(jScrollPane2, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 330, 220, 70));
            send.setText("Send");
            send.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    sendActionPerformed(evt);
            getContentPane().add(send, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 420, -1, -1));
            jMenu1.setText("File");
            jMenu1.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jMenu1ActionPerformed(evt);
            jMenuBar1.add(jMenu1);
            jMenu2.setText("Option");
            jMenuBar1.add(jMenu2);
            setJMenuBar(jMenuBar1);
            pack();
        // </editor-fold>                       
        private void sendActionPerformed(java.awt.event.ActionEvent evt) {                                    
            String text = txt_messege.getText();
            out.println();
            txt_messege.setText(new String(""));
            convo_txt.append(text);
        private void jMenu1ActionPerformed(java.awt.event.ActionEvent evt) {                                      
    // TODO add your handling code here:
         * @param args the command line arguments
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new ChatDialog_c().setVisible(true);
        }///////////////////////chat dialog thread/////////////////////
    package icomm;
    import java.net.*;
    import java.io.*;
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    public class ChatDialog extends javax.swing.JFrame implements WindowListener, Runnable {
        protected String messege;
        private Socket client_user = null;
        /** Creates new form ChatDialog */
        public ChatDialog()
            initComponents();
            addWindowListener( this );
        public ChatDialog(String txt_messege)
            initComponents();
            addWindowListener( this );
            this.messege = txt_messege;
         public ChatDialog(Socket user)
             initComponents();
             addWindowListener( this );
             this.client_user = user;
        public void run()
            BufferedReader in = null;
            PrintWriter out = null;
            String error = "error has occured ";
            String messege = null;
             try
                //create input and output streams
                in = new BufferedReader(new InputStreamReader (client_user.getInputStream()));
                out = new PrintWriter(client_user.getOutputStream(), true);
                while(true)
                   //read messege sent by user
                   messege = in.readLine();
                   //send data back to user
                   out.println(messege);
                   //append data on the text field
                   convo_txt.append(messege + "\n");
                   //chat_gui.setVisible(true);
                   //-=inputs = new ChatDialog(messege);
               //out.close();
                //in.close();
                //client_user.close();
            catch (IOException e)
                //error messege
                e.printStackTrace();
                JOptionPane.showMessageDialog(null, error + e.getMessage(), null, JOptionPane.ERROR_MESSAGE);
        }If I can sort this problem out I would of completed the main part of my program. I have spent days on this and hope that anyone of you guys can take the time out and help me with my current situation. Thanks

    update:
    i have managed to sort out the connection refused
    i know have anotehr problem: both client2 program freezes as soon as client 1 tries to initiate a connection to client 2!!!!!!!!
    when client 2 logs into teh system. it freezes as soon as i press the button! but when client 1 attempts to conenct to client 2, client 2's program stops freezing and the chatdialog comes up showing nothing and freezes! my chadialog is suppose to show a file menu i made but it doesnt,. both clients freezes at this point. no error messeges occur...

  • Conflict between socket and RMI

    Hi
    I wrote a program in client-server using socket and it was fine. I also wrote a client-server program using RMI. Fine as well. But after I connected the client-server using socket (open socket, send-receive messages, close socket), then use RMI. I got java.rmi.NotBoundException.
    Would anyone have a look and provide your feedback please? Thanks.
    big J
    *****************this is Server.java ***************************
    package single;
    import java.io.*;
    import java.rmi.Naming;
    import java.rmi.RemoteException;
    import java.net.*;
    import java.rmi.*;
    public class Server
    extends Thread {
    public static final int SOCKETPORT = 5555;
    private String serverName;
    public Server() throws IOException {
    System.out.println("*** socket opened ***");
    serverName = new String("localhost");
    ServerSocket serverSocket = new ServerSocket(SOCKETPORT);
    Socket socket = serverSocket.accept();
    InputStream is = socket.getInputStream();
    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(is));
    System.out.println(bufferedReader.readLine());
    OutputStream os = socket.getOutputStream();
    PrintWriter printWriter = new PrintWriter(new OutputStreamWriter(os), true);
    printWriter.println("from server");
    os.close();
    is.close();
    socket.close();
    System.out.println("*** socket closed ***");
    public void runServer() {
    System.out.println("*** start of run():RMI ***");
    System.setSecurityManager(new SecurityManager());
    try {
    RMIInterfaceImpl rMIInterfaceImpl = new RMIInterfaceImpl();
    Naming.bind("//" + serverName + ":9999/RMIInterface", rMIInterfaceImpl);
    catch (RemoteException ex) {
    catch (MalformedURLException ex) {
    catch (AlreadyBoundException ex) {
    System.out.println("*** end of run():RMI ***");
    public static void main(String args[]) throws Exception {
    Server server = new Server();
    server.runServer();
    ******************this is Client.java **************************
    package single;
    import java.io.*;
    import java.net.*;
    import java.rmi.Naming;
    public class Client {
    private String serverName;
    private final static int SOCKETPORT = 5555;
    public Client() throws IOException {
    serverName = new String("localhost");
    Socket socket = new Socket(serverName, SOCKETPORT);
    OutputStream os = socket.getOutputStream();
    PrintWriter printWriter=new PrintWriter(os, true);
    printWriter.println("from client");
    InputStream is = socket.getInputStream();
    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(is));
    System.out.println(bufferedReader.readLine());
    is.close();
    os.close();
    socket.close();
    public void runClient() throws Exception {
    System.out.println("*** start of runClient():RMI ***");
    System.setSecurityManager(new SecurityManager());
    RMIInterface rMIInterfaceImpl = (RMIInterface) Naming.lookup(
    "//" + serverName + ":9999/RMIInterface");
    String str = rMIInterfaceImpl.print();
    System.out.println(str);
    rMIInterfaceImpl.serverSide();
    System.out.println("*** end of runClient():RMI ***");
    public static void main(String args[]) throws Exception {
    Client client = new Client();
    client.runClient();
    ***************** this is RMIInterface.java ***********************
    package single;
    import java.rmi.Remote;
    import java.rmi.RemoteException;
    interface RMIInterface
    extends Remote {
    String print() throws RemoteException;
    void serverSide() throws RemoteException;
    ********************* this is RMIInterfaceImpl.java ***************
    package single;
    import java.rmi.RemoteException;
    import java.rmi.server.UnicastRemoteObject;
    public class RMIInterfaceImpl
    extends UnicastRemoteObject
    implements RMIInterface {
    public RMIInterfaceImpl() throws RemoteException {}
    public String print() {
    return new String("hello world");
    public void serverSide(){
    System.out.println("this should appear in serverside");

    I think you have a timing problem between your client and server. As soon as your client and server programs have finished their socket communication, they will both do their "runServer"/"runClient" methods. If the client attempts to lookup the server before the server has registered itself via Naming.bind(), I would expect that's why you're getting a NotBoundException in the client.
    You probably wouldn't use the design of your test client/server for something significant, but a quick and dirty way to make this work might be to have the client call Thread.sleep() for a few seconds before trying to do the lookup.

  • How can i reuse my existing socket connection

    Hi,
    this might sound basic, it probably is:
    As part of my larger project, i have to send and recieve data to multiple socket connections.
    The thing that happens is that everytime i send data, it seems that java is creating a new stream or something (code is multithreaded)
    so as i send 4 items of data, a bit like a chat program sending 4 statements, it creates 4 different streams, instead of using the same stream. therefore when i close the connection, i get:
    java.net.SocketException: Connection reset 4 times.
    i know why.. its because i have added the:
    Socket socket=new Socket(host, port);
    BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    PrintWriter out = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
    bit in the same method with the
    out.println(THE DATA....);
    out.flush();
    The thing what i want to do is to create the connection one, and reuse the objects:
    out, in and socket
    to send / recieve the new data.
    please help me guys,
    thanks

    All the threads would be able to get the same reference to....
    class SocketWrapper {
         private final Object readLock = new Object();
         private final Object writeLock = new Object();
         // client side
        public SocketWrapper(String hostname, int port);
         // server side.
        public SocketWrapper(Socket);
         // send data
         public void send(Serializable object) throws IOException;
         // receive data. synchronized(writeLock);
         public Serializable getNext() throws IOException;
         // create a new socket as required, throw IllegalState if server side. synchronized(readLock)
         private void createNewSocket() throws IllegalStateException;
    }The send autoconnects as required. It then send on message/packet/object.
    The getNext autoconnects as required. It reads one message/packet/object and returns.
    This allows multiple threads to access the same socket. It allows data to be sent while a thread is blocking on a read. (Thus two locks)

  • How can i create a socket connection through an http proxy

    i'm trying to make a socket connection send an email - i have code that works when you don't have to go through a proxy server but i can't make it pass the proxy server.
    import java.net.*;
    import java.io.*;
    import java.util.*;
    public class Mail
    public String to_address = "[email protected]";
    public String from_address = "[email protected]";
    public String sendSub = "HeHeHe";
    public String sendBody = "hehehe - it worked";
    // This is created to allow data to be read in by the keyboard.
    BufferedReader in = new BufferedReader(
    new InputStreamReader(System.in));
         private void Mail(String to_address, // recipient's addresses
    String from_address, // sender's address
    String sendSub, // subject
    String sendBody) // Message
                   throws IOException, ProtocolException,      UnknownHostException {
         Socket socket;                // creates a Socket named socket
         PrintStream out;               // stream to write to socket
         String host = "imap.btopenworld.com";          // identification of the mail server host
    // creates a new socket for connection to the mail server
    // as well as two variables for the read and write streams
         socket = new Socket(host, 25); // opens socket to host on port 25 (SMTP port)
         out = new PrintStream(socket.getOutputStream());
    // read the initial message
         in.readLine();
    // Dialog with the mail server
    // send HELO to SMTP server HELO command is given by a connecting SMTP host
         out.println( "HELO " + host );
         out.flush() ;
         in.readLine();
    // Once we are connected to the mail server we start sending the email...
    // send "from"
         out.println( "MAIL FROM: " + from_address );
         out.flush() ;
         in.readLine();
    // send "to"
         out.println( "RCPT TO: " + to_address );
         out.flush() ;
         in.readLine();
    // prepare the mailserver to receive the data
         out.println( "DATA" );
         out.flush() ;
         in.readLine();
    // Send actual email
         out.println("From: " + from_address);
         out.println("To: " + to_address);
         out.println( "Subject: " + sendSub + "\n" );
         out.flush() ;
         out.println("");
         out.println( sendBody ) ;
         out.println(".") ; // standard to determine end-of-body
         out.flush() ;
         in.readLine();
    //Quit and closes socket
         out.println("QUIT");
         out.flush();
         in.close() ;
         socket.close() ;
         return ;
    public static void main (String [] args) throws IOException
    Mail themail = new Mail();
    }

    i've tried that but it doesn't seem to do nething - this is how i implemented it...
    import java.net.*;
    import java.io.*;
    import java.util.*;
    public class Mail
    public String to_address = "[email protected]";
    public String from_address = "[email protected]";
    public String sendSub = "HeHeHe";
    public String sendBody = "hehehe - it worked";
    // This is created to allow data to be read in by the keyboard.
    BufferedReader in = new BufferedReader(
    new InputStreamReader(System.in));
         private void Mail(String to_address, // recipient's addresses
    String from_address, // sender's address
    String sendSub, // subject
    String sendBody) // Message
                   throws IOException, ProtocolException,      UnknownHostException {
         Socket socket;                // creates a Socket named socket
         PrintStream out;               // stream to write to socket
         String host = "imap.btopenworld.com";          // identification of the mail server host
    // creates a new socket for connection to the mail server
    // as well as two variables for the read and write streams
         socket = new Socket(host, 25); // opens socket to host on port 25 (SMTP port)
         out = new PrintStream(socket.getOutputStream());
    // read the initial message
         in.readLine();
    System.getProperties().put( "proxySet", "true" );
              System.getProperties().put( "proxyHost", "144.124.16.28" );
              System.getProperties().put( "proxyPort", "8080" );
    // Dialog with the mail server
    // send HELO to SMTP server HELO command is given by a connecting SMTP host
         out.println( "HELO " + host );
         out.flush() ;
         in.readLine();
    // Once we are connected to the mail server we start sending the email...
    // send "from"
         out.println( "MAIL FROM: " + from_address );
         out.flush() ;
         in.readLine();
    // send "to"
         out.println( "RCPT TO: " + to_address );
         out.flush() ;
         in.readLine();
    // prepare the mailserver to receive the data
         out.println( "DATA" );
         out.flush() ;
         in.readLine();
    // Send actual email
         out.println("From: " + from_address);
         out.println("To: " + to_address);
         out.println( "Subject: " + sendSub + "\n" );
         out.flush() ;
         out.println("");
         out.println( sendBody ) ;
         out.println(".") ; // standard to determine end-of-body
         out.flush() ;
         in.readLine();
    //Quit and closes socket
         out.println("QUIT");
         out.flush();
         in.close() ;
         socket.close() ;
         return ;
    public static void main (String [] args) throws IOException
    Mail themail = new Mail();
    }

  • Multiple OutputStreams to a single socket

    Hi,
    I searched the forums but could not find an answer for this.
    I have a socket between a server and a client and am already using an output stream to send information via this output stream.
    Now, I want to use another thread and another output stream to the same socket to send more data to the client. Is this possible? Are there synchronization problems or would the messages from both threads clutter each other in the socket? Is the multiplexing between the (text) messages from the 2 streams done in the lower layers of the TCP socket? Can I get away with using this or should I redesign my means of communication? I might also move towards object serialization in the future for my messages.
    I wrote two sample programs and the result looks ok, but I want to check to see if there are no issues with this. The test client creates 3 threads that get different output streams from the same socket and then send their name to the server independently and randomly. The server receives text messages via the socket and prints them out. I do flush all me messages and only send text messages. From the output it looks like the messages are not clobbered and are received randomly. I also did the test without the randomness and saw no problems.
    thanks,
    Clive.
    My server code:
    import java.io.*;
    import java.net.*;
    public class EchoServer {
      public static void main(String[] args) throws IOException {
        Socket echoSocket = null;
        PrintWriter out = null;
        BufferedReader in = null;
        try {
          System.out.println("Starting server... ");
          ServerSocket serverSocket = new ServerSocket(60000);
          System.out.println("Waiting for client at 60000 ... ");
          echoSocket = serverSocket.accept();
          System.out.println("Connected to client at 60000");
          in = new BufferedReader(new InputStreamReader(
                                      echoSocket.getInputStream()));
        } catch (UnknownHostException e) {
          System.err.println("Don't know about host: " + e.getMessage());
          System.exit(1);
        } catch (IOException e) {
          System.err.println("Couldn't get I/O for "
                             + "the connection to: " + e.getMessage());
          System.exit(1);
        String userInput;
        while ((userInput = in.readLine()) != null) {
          System.out.println("echo: " + userInput);
        System.out.println("Closing the socket");
        in.close();
        echoSocket.close();
      } // main
    }My client code:
    import java.io.*;
    import java.net.*;
    import java.util.*;
    public class EchoClient {
      public EchoClient() {
        Socket echoSocket = null;
        PrintWriter out1 = null;
        BufferedReader in = null;
        MyWriter thread1 = null;
        MyWriter thread2 = null;
        MyWriter thread3 = null;
        try {
          System.out.println("Connecting to localhost");
          echoSocket = new Socket("localhost", 60000);
          thread1 = new MyWriter(echoSocket, "name1");
          thread1.start();
          thread2 = new MyWriter(echoSocket, "name2");
          thread2.start();
          thread3 = new MyWriter(echoSocket, "name3");
          thread3.start();
        } catch (UnknownHostException e) {
          System.err.println("Don't know about host: " + e.getMessage());
          System.exit(1);
        } catch (IOException e) {
          System.err.println("Couldn't get I/O for "
                             + "the connection to: " + e.getMessage());
          System.exit(1);
      } // cons
      public class MyWriter extends Thread {
        PrintWriter out = null;
        String name;
        public  MyWriter(java.net.Socket socket, String name) {
          super(name);
          try {
            out = new PrintWriter(socket.getOutputStream(), true);
            this.name = name;
          } catch (IOException ioe) {
            System.err.println("Could not get output stream for " + name);
        public void run() {
          String userInput;
          Random r = new Random();
          boolean myTruth = true;
          try {
            while(myTruth) {
              out.println( this.name );
              System.out.println("sent " + this.name);
              Thread.sleep(r.nextInt(200));  // send the info randomly
          } catch(InterruptedException ie) {
            System.err.println("Could not wait for " + name);
          out.close();
      } // class MyWriter
      public static void main(String[] args) throws IOException {
        EchoClient echo = new EchoClient();
      } // main
    }Server Output:
    Connected to client at 60000
    echo: name1
    echo: name2
    echo: name3
    echo: name1
    echo: name2
    echo: name3
    echo: name1
    echo: name2
    echo: name3
    echo: name3
    echo: name1
    echo: name2
    echo: name3
    echo: name1
    echo: name1

    It is certainly doable, but you'll need to do some work here.
    Probably what i would do is write a Multiplexor stream that sits on top of the raw tcp stream.
    Implement this stream to implement synchronization such that only one client stream can write at a time. Further each stream should have a unique id associated with it, and registered with the base Multiplexor stream, so that when it writes into the down stream, it can prefix the data with its id. In that way the reader of the stream can see where to forward the data to.
    If some other stream tries to write to the Base Multiplexor stream an exception should be thrown, since it hasn't registered itself.
    There is a book by Manning that is pretty good in this area.
    http://www.manning.com/Hughes/

Maybe you are looking for

  • Java Instalation Failed. ~Please Help?~

    When i get to the installation step of download Java Version 6 Update 16 this error shows up. Error Msg: Installation Failed The wizard was interrupted before Java(TM) 6 Update 16 could be completely installed. To complete installation at another tim

  • Material Cost Transaction Worker in Warning

    Hi Guys I'm trying to do, what I thought was the simplest costing transaction. I create one item. I create a PO. Do a receipt. And now I want to do the cost accounting (STD Costing) for this transaction. I have frozen costs against the item. The cost

  • Yosemite error 150:30. Photoshop CS4

    Hard drive was failing so new hard drive and Yosemite. Now I get an error when trying to launch PS CS4. Error code 150:30 Licensing for this product has stopped working. Any ideas? Don't want to upgrade.

  • SUID ?

    Hello - I needed to clean permissions, and now I'm left with a cryptic (for me, at any rate) message: "Warning: SUID file "System/Library/CoreServices/RemoteManagement/ARDAgent.app/Contents/MacOS/ARDAg ent" has been modified and will not be repaired.

  • Why is my mac book running so slow?

    I noticed that my mac book was running slower than normal. I had recently downloaded alot of HD video off my video camera so I had thought that was the reason. I installed a new 250 gb hard drive and upgraded to 2 gb of ram and it did not improve at