Socket Client/Server

I have an app using the Client/Server socket connections. Only problem is if the server should drop out and then get restarted, how can I detect the event from the client socket connection. At the moment on fail to send data I attempt to re-connect to the server; but it may actually be a diff error.
Thanks in advance

while (i > 0) {This loop terminates when the server closes the socket. If the server doesn't close the socket it will block in the read() method. So you'll never get to the next part. So either have the server close the socket or arrange your application protocol so you can tell when you've received a complete reply.

Similar Messages

  • How to design socket client-server app for 2-way communication

    Hi, I am writing a client-server application. I have a single server and many clients. Each client will need the ability to send information to the server at any time. The server will also need the ability to send information to a client at any time. Its this second part that I am not sure how to design. Would I need to create a SocketServer on each client to accept incoming messages, or is there a better way? Thanks

    scranchdaddy wrote:
    Don't my requirements sound a lot like an IM application, where a chat server might need to send a message to a chat client at any time?Not really. If that is what you are designing
    in my opinion one could easily be forgiven for thinking you were deliberately obfuscating your goal...
    How does the server know where the client is? Does it know the IP address of the client?I would imagine the server would contain a directory of IPs? I'm not sure.
    What happens if the client is not running?Then I guess the message would not get delivered.
    What happens if the client is behind a firewall that does not allow incoming connections?How do IM chat clients work? How have people solved this in the past?Typically the server would only care about clients currently connected to the server.
    Maybe you should re-think your design. I don't really have a design, just requirements, that's why I'm writing this post.Your subject says "+How to *design* socket client-server app for 2-way communication+".
    Are you saying you expect someone else to do the design for you?

  • Client/server

    Hi, i am doing a client/server arc .I have a server , that will connected to the oracle , using jdbc.The client here is an application, how do i change it to applet?
    The server code
    import java.sql.*;
    import java.util.Properties;
    import java.io.*;
    import java.net.*;
    public class CommentsServer extends Thread {
    public static final int DEFAULT_PORT = 7777;
    protected int port;
    protected ServerSocket server;
    String username ="combtest";
    String password = "combtest";
    public static void main (String args[]) {
    int port=0;
    if (args.length == 1) {
    try {
    port = Integer.parseInt (args[0]);
    } catch (NumberFormatException e) { }
    try {
         Class.forName("oracle.jdbc.driver.OracleDriver");
    String sourceURL ="jdbc:oracle:thin:@klm:1521:KLMPMIS";
    String user="combtest";
    String password="combtest";
    catch (Exception e) {
    System.err.println("Failed to load JDBC driver.");
    System.exit (1);
    new CommentsServer (port);
    public CommentsServer (int port) {
    super ("Comments Server");
    if (port == 0)
    port = DEFAULT_PORT;
    this.port = port;
    try {
    server = new ServerSocket (port);
    } catch (IOException e) {
    System.err.println ("Error creating server");
    System.exit (1);
    start();
    public void run() {
    System.out.println ("Server Running");
    ThreadGroup connections = new ThreadGroup ("Comment Connections");
    connections.setMaxPriority(this.getPriority()-1);
    try {
    while (true) {
    Socket client = server.accept();
    System.out.println ("Connection from: " + client.getInetAddress().getHostName());
    CommentsConnection c = new CommentsConnection (connections, client);
    } catch (IOException e) {
    System.err.println ("Exception listening");
    System.exit (1);
    System.exit (0);
    class CommentsConnection extends Thread {
    static int counter = 0;
    protected ObjectInputStream in;
    protected PrintWriter out;
    public CommentsConnection (ThreadGroup group, Socket client) {
    super (group, "Connection " + counter++);
    try {
    in = new ObjectInputStream (client.getInputStream ());
    out = new PrintWriter (client.getOutputStream(), true);
    } catch (IOException e) {
    try {
    client.close();
    } catch (IOException e2) { }
    System.err.println ("Unable to connect.");
    return;
    start();
    public void run () {
    try {
    String mode = (String)in.readObject();
    if (mode.equals("insert")) {
         String name=(String)in.readObject();
    try {
         String u="jdbc:oracle:thin:@klm:1521:KLMPMIS";
         Connection con=DriverManager.getConnection(u,"combtest","combtest");
         PreparedStatement prep=con.prepareStatement("Insert into TEST values(?)");
         prep.setString(1,name);
         if(prep.executeUpdate()!=1)
         throw new Exception("Bad update");
    } catch (Exception e) {
    out.println ("Error updating: " + e);
    return;
    } else if (mode.equals("query")) {
    try {
         Connection con=DriverManager.getConnection("jdbc:oracle:thin:@klmsph1:1521:KLMPMIS","combtest","combtest");
    Statement statement=con.createStatement();
    ResultSet result=statement.executeQuery("SELECT * FROM TEST");
    out.println("Name");
    int nameCol=result.findColumn("NAME");
    String name,user,comments;
    while(result.next())
         name=result.getString(nameCol);
         out.println(name);
    statement.close();
    con.close();
    } catch (Exception e) {
    out.println ("Error querying: " + e);
    return;
    } else {
    out.println ("Invalid Command: " + mode);
    } catch (Exception e) {
    out.println ("Error reading Stream: " + e);
    out.close();
    the client code
    import java.net.*;
    import java.io.*;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class CommentsClient extends JApplet{
    TextArea ta;
    TextField name;     
    public static final int DEFAULT_PORT = 7777;
    private static final String QueryString = "query";
    private static final String InsertString = "insert";
    private int port = 0;
    private String host = null;
    private OutputStream os = null;
    public CommentsClient (String host, int port, OutputStream os) {
    this.host = host;
    this.port = ((port == 0) ? DEFAULT_PORT : port);
    this.os = os;
    query();
    public CommentsClient (String host, int port, OutputStream os,
    String name) {
    this.host = host;
    this.port = ((port == 0) ? DEFAULT_PORT : port);
    this.os = os;
    insert(name);
    private void query () {
    PrintWriter out = new PrintWriter (os, true);
    try {
    Socket s = new Socket (host, port);
    ObjectOutputStream oos = new ObjectOutputStream (s.getOutputStream());
    // PrintWriter out=new PrintWriter(s.getOutputStream(),true);
    oos.writeObject (QueryString);
    oos.flush();
    BufferedReader in = new BufferedReader (new InputStreamReader (s.getInputStream()));
    String line;
    while ((line = in.readLine()) != null) {
    out.println (line);
    out.close();
    s.close();
    } catch (IOException e) {
    out.println ("Error querying." + e);
    return;
    private void insert (String name) {
    PrintWriter out = new PrintWriter (os, true);
    try {
    Socket s = new Socket (host, port);
    ObjectOutputStream oos = new ObjectOutputStream (s.getOutputStream());
    oos.writeObject (InsertString);
    oos.writeObject (name);
    oos.flush();
    BufferedReader in = new BufferedReader (new InputStreamReader (s.getInputStream()));
    String line;
    while ((line = in.readLine()) != null) {
    out.println (line);
    oos.close();
    s.close();
    } catch (IOException e) {
    out.println ("Error inserting." + e);
    return;
    public static void main (String args[]) {
    if (args.length == 0) {
    CommentsClient cc = new CommentsClient ("localhost", 0, System.out);
    } else if (args.length == 1) {
    CommentsClient cc = new CommentsClient ("localhost", 0, System.out, args[0]);
    the applet (acts as an interface)
    import java.awt.*;
    import java.awt.event.*;
    import java.applet.Applet;
    import java.io.*;
    //<applet code = "CommentsApplet" width = 800 height = 600>
    //</applet>
    public class CommentsApplet extends Applet {
    TextArea ta;
    TextField name;
    TextField user;
    TextField comments;
    public void init () {
    Panel p1 = new Panel(new BorderLayout(10, 10));
    Button b1 = new Button ("Query");
    p1.add (b1, BorderLayout.SOUTH);
    ta = new TextArea ();
    ta.setEditable(false);
    p1.add (ta, BorderLayout.CENTER);
    b1.addActionListener (new ActionListener() {
    public void actionPerformed (ActionEvent e) {
    ByteArrayOutputStream bao = new ByteArrayOutputStream();
    CommentsClient cc = new CommentsClient ("localhost", 0, bao);
    ta.setText (bao.toString());
    add (p1);
    Panel p2 = new Panel (new BorderLayout (10, 10));
    Button b2 = new Button ("Insert");
    p2.add (b2, BorderLayout.SOUTH);
    Panel p3 = new Panel();
    name = new TextField ("", 10);
    p3.add (name);
    p2.add (p3, BorderLayout.CENTER);
    b2.addActionListener (new ActionListener() {
    public void actionPerformed (ActionEvent e) {
    ByteArrayOutputStream bao = new ByteArrayOutputStream();
    CommentsClient cc = new CommentsClient ("localhost", 0, bao, name.getText());
    ta.setText (bao.toString());
    add (p2);
    the html file
    <html>
    <body>
    <hr>
    <applet
    code=CommentsApplet.class
    width = 400
    height = 400
    >
    </applet>
    <hr>
    </body>
    </html>
    Thanks in advance,
    Jessy

    hi
    I have no idea what you are doing. Strange programming
    public class CommentsClient extends JApplet why does it extends JApplet when it isn't a JApplet but an application
    and why is there a second applet
    public class CommentsApplet extends Applet (should this be extends JPanel??)
    but for normal classes this is the procedure
    rename the constructor in "public void init()" the method init is automaticly called by the browser.
    remove the main method if there is some code in the main method that needed move it to the init method. ( in your case the arguments can't be read from the command line but must be read out of the *.html file )

  • Client/Server API with push?

    I set up a simple Socket client server architecture with the Java socket API. However, my clients sometimes are initiators or requests, and sometimes my server is the initiator of infos. Example: client want to get infos from server but also want to tell the server something. The server tells all registered clients something but also can accept requests from clients. So both sides are client AND server (depending on what they currently want to do).
    The socket API is just a classic client/server API, i.e. a server listens and a client sends requets and get responses. For my server to send requests to all clients, this is not enough. Is the only way to have all clients offering a socket server on their computer, too? so that this 2-way-request-communication works?
    This is basically some kind of "push" technology, but i don't want my clients to "poll" the server just to emulate the feature of sending requests from the server to the client. Is there some other (perhaps non-socket) API that offers this?

    @sjasja: how is the socket api symmetrical?It is, trust me! Connection initiation isn't, but after that it is. (Let's assume connected TCP/IP.)
    The server does bind() and accept(), the client does connect(). After that, the connection is symmetrical: either end can issue any number of read() and write() calls in any order. You write() to a socket, it pops out from read() at the other end (though not necessarily as a single packet; TCP/IP is stream oriented, so write() "packets" can and will be glued together, or fragmented at the whimsy of network routers and friends.)
    - accept() //wait for client to send request
    - socket.getInputStream() //read request
    - socket .getOutputStream() //write responseThose don't read or write; they get streams which you can read from and write to.
    In the server, when accept() returns a new connection, you'd start a reader thread for that client. The thread would read() (or readLine() if you implement a line-oriented protocol) and handle the incoming messages. Whenever you want to write to the client, write to the stream returned by socket.getOutputStream(). You may need to synchronize writes if you have several threads that do sequences of write()s that need to arrive at the client sequentially.
    As to the difficulty of socket programming: I don't think it particularly difficult. But then I've written dozens of socket programs since my first one in '85... The Java Tutorial socket chapter shows a simple client/server pair; not terribly difficult I think. In particular, check out the KKMultiServer at the bottom of the sample server chapter.

  • Best practice for client-server(Socket) application

    I want to build a client-server application
    1) On startup.. client creates connection to Server and keeps reading data from server
    2) Server keeps on sending different messages
    3) Based on messages(Async) from server client view has to be changed
    I tried different cases ended up facing IllegalStateChangeException while updating GUI
    So what is the best way to do this?
    Please give a working example .
    Thanks,
    Vijay
    Edited by: 844427 on Jan 12, 2012 12:15 AM
    Edited by: 844427 on Jan 12, 2012 12:16 AM

    Hi EJP,
    Thanks for the suggestion ,
    Here is sample code :
    public class Lobby implements LobbyModelsChangeListener{
        Stage stage;
        ListView<String> listView;
        ObservableList ol;
         public Lobby(Stage primaryStage) {
            stage = primaryStage;
               ProxyServer.startReadFromServer();//Connects to Socket Server
             ProxyServer.addLobbyModelChangeListener(this);//So that any data from server is fetched to Lobby
            init();
        private void init() {
              ProxyServer.getLobbyList();//Send
            ol = FXCollections.observableArrayList(
              "Loading Data..."
            ol.addListener(new ListChangeListener(){
                @Override
                public void onChanged(Change change) {
                    listView.setItems(ol);
         Group root = new Group();
        stage.setScene(new Scene(root));
         listView = new ListView<String>();
        listView.maxWidth(stage.getWidth());
         listView.setItems(ol);
         listView.getSelectionModel().setSelectionMode(SelectionMode.SINGLE);
        istView.setOnMouseClicked(new EventHandler<MouseEvent>(){
                @Override
                public void handle(MouseEvent t) {
    //                ListView lv = (ListView) t.getSource();
                    new NewPage(stage);
         root.getChildren().add(listView);
         @Override
        public void updateLobby(LobbyListModel[] changes) {
    //        listView.getItems().clear();
            String[] ar = new String[changes.length];
            for(int i=0;i<changes.length;i++)
                if(changes!=null)
    System.out.println(changes[i].getName());
    ar[i] = changes[i].getName();
    ol.addAll(ar);
    ProxyServer.javaProxyServer
    //Implements runnable
    public void run()
         ......//code to read data from server
    //make array of LobbyListModel[] ltm based on data from server
         fireLobbyModelChangeEvent(ltm);
    void addLobbyModelChangeListener(LobbyModelsChangeListener aThis) {
    this.lobbyModelsChangeListener = aThis;
         private void fireLobbyModelChangeEvent(LobbyListModel[] changes) {
    LobbyModelsChangeListener listner
    = (LobbyModelsChangeListener) lobbyModelsChangeListener;
    listner.updateLobby(changes);
    Exception :
    java.lang.IllegalStateException: Not on FX application thread; currentThread = Thread-5
             at line         ol.addAll(ar);
    But ListView is getting updated with new data...so not sure if its right way to proceed...
    Thanks,
    Vijay                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • FU Ant task failure: java.util.concurrent.ExecutionException: could not close client/server socket

    We sometimes see this failure intermitently when using the FlexUnit Ant task to run tests in a CI environment. The Ant task throws this exception:
    java.util.concurrent.ExecutionException: could not close client/server socket
    I have seen this for a while now, and still see it with the latest 4.1 RC versions.
    Here is the console output seen along with the above exception:
    FlexUnit player target: flash
    Validating task attributes ...
    Generating default values ...
    Using default working dir [C:\DJTE\commons.formatter_swc\d3flxcmn32\extracted\Source\Flex]
    Using the following settings for the test run:
    FLEX_HOME: [C:\dev\vert-d3flxcmn32\302100.41.0.20110323122739_d3flxcmn32]
    haltonfailure: [false]
    headless: [false]
    display: [99]
    localTrusted: [true]
    player: [flash]
    port: [1024]
    swf: [C:\DJTE\commons.formatter_swc\d3flxcmn32\extracted\build\commons.formatter.tests.unit.sw f]
    timeout: [1800000ms]
    toDir: [C:\DJTE\commons.formatter_swc\d3flxcmn32\reports\xml]
    Setting up server process ...
    Entry  [C:\DJTE\commons.formatter_swc\d3flxcmn32\extracted\build] already  available in local trust file at  [C:\Users\user\AppData\Roaming\Macromedia\Flash  Player\#Security\FlashPlayerTrust\flexUnit.cfg].
    Executing 'rundll32' with arguments:
    'url.dll,FileProtocolHandler'
    'C:\DJTE\commons.formatter_swc\d3flxcmn32\extracted\build\commons.formatter.tests.unit.swf '
    The ' characters around the executable and arguments are
    not part of the command.
    Starting server ...
    Opening server socket on port [1024].
    Waiting for client connection ...
    Client connected.
    Setting inbound buffer size to [262144] bytes.
    Receiving data ...
    Sending acknowledgement to player to start sending test data ...
    Stopping server ...
    End of test data reached, sending acknowledgement to player ...
    When the problem occurs, it is not always during the running of any particular test (that I am aware of). Recent runs where this failure was seen had the following number of tests executed (note: the total number that should be run is 45677): 18021, 18, 229.
    Here is a "good" run when the problem does not occur:
    Setting inbound buffer size to [262144] bytes.
    Receiving data ...
    Sending acknowledgement to player to start sending test data ...
    Stopping server ...
    End of test data reached, sending acknowledgement to player ...
    Closing client connection ...
    Closing server on port [1024] ...
    Analyzing reports ...
    Suite: com.formatters.help.TestGeographicSiteUrls
    Tests run: 5, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.008 sec
    Suite: com.formatters.functionalUnitTest.testCases.TestNumericUDF
    Tests run: 13, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.071 sec
    Results :
    Tests run: 45,677, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 201.186 sec
    Has anyone else ran across this problem?
    Thanks,
    Trevor

    I am not sure if this information will help everyone, but here goes...
    For us, these problems with FlexUnit tests crashing the Flash Player appear to be related to couple of factors. Recently, we moved up from Flex 3.2 to Flex 4.1 as our development baseline.  Many people complained that their development environment (Flash Builder, etc.) was much more unstable.  Apparently, 4.1 produces SWFs that require more memory to run than 3.2 does?  Anyway, we still had Flash Player 10.1 as our runtime baseline.  Apparently, that version of the player was not as capable of running larger FlexUnit test SWFs, and would crash (as I posted months earlier).  I upgraded to the latest 10.3 standalone player versions, and the crashes have now ceased.  It would be nice to know exactly what was causing the crashes, but memory management (or lack of) is my best guess.
    So, if you are seeing these issues, try upgrading to the latest Flash Player version.
    Regards,
    Trevor

  • Publishing .fla project including client - server socket connection

    Hi,
    I have designed with Adobe Flash Professional CS5 a .fla project that integrates a client - server connection.
    After publishing it, I have the following issue:
    - when running the generated .exe file for Windows, then the connection to the server works perfectly
    - but when I am running the published .html file, then nothing is sent to the server.
    I have tried to change the Publish Settings.
    When setting the Local Playback Security in Flash menu to "Access network only" instead of "Access local files only" then the last packet that was send using the .exe file is resent once and that's all (the html client does not receive the response from the server and the next connection attemps generate data transfer).
    I guess I have to change some security settings somewhere but I didn't find which.
    Does anybody have a hint ?
    Thanks.

    Hi again,
    I was finally able to solve the issue.
    I did not get any error message when using firefox, but using iExplorer provided me this error:
    "Local-with-filesystem SWF files are not permitted to use sockets"
    Googling did then allow me to find the solution here:
    http://www.macromedia.com/support/documentation/en/flashplayer/help/settings_manager04.htm l
    The local locations on which I store my html page during the development has to be added to the trusted locations in the global security settings.
    Hope it will help some other people.
    Best regards

  • Should i use secure sockets for my whole client/server application?

    Hi,
    I have a client server application, and I want to ensure that the login process is secure (i.e. use secure sockets). but I dont know how to switch back to a normal socket once that is done.
    So I am left thinking that i should just use SSL for my whole application, which can last pretty long. But I would rather not. Is there any other way of doing this?
    or should I just encrypt the login info using MD5 or something like that, then send it over an unsecure socket?
    thanks!

    Hey,
    Are you sure you haven't confused JGSS for JSSE?
    Imagine you have a client-server system and you sometimes want data sent over the wire to be encrypted... JGSS offers you this flexibility; if you a encrypted transmission, run ift through JGSS before transmitting it; if you don't want an encrypted transmission, bypass JGSS and just send the transmission.
    The benefit is the security (encryption) isn't hard-wired into you communications protocol i.e. TLS. JGSS has nothing to do with connections it is just protocol for securing messages, not sending them.
    You would need to establish the secure context but this could be done at startup and persist for the duration of you applicaiton invocation. You perhaps might need to implement a mechanism to identify encrypted messages on the receiving peer (so it knows to attempt decryption).
    Admittedly, kerberos seems like one of those 'inside-joke' things. I've come to realise if you don't have some sort of kerberos realm/server against which to authenticate - you need to swap it out as the underlying mechanism. How this is done I'm not sure yet, but I intend to find out today....further down the rabbit hole I go!
    If I discover anything helpful, I will let you know.
    Warm regards,
    D

  • Applet socket problem in client-server, urgent!

    Dear All:
    I have implemented a client server teamwork environment. I have managered to get the server running fine. The server is responsible for passing messages between clients and accessing Oracle database using JDBC. The client is a Java Applet. The code is like the following. The problem is when I try to register the client, the socket connection get java.security.AccessControlException: access denied(java.net.SocketPermission mugca.its.monash.edu.
    au resolve)
    However, I have written a Java application with the same socket connection method to connect to the same server, it connects to the server without any problem. Is it because of the applet security problem? How should I solve it? Very appreciate for any ideas.
    public class User extends java.applet.Applet implements ActionListener, ItemListener
    public void init()
    Authentication auth = new Authentication((Frame)anchorpoint);
    if(auth.getConnectionStreams() != null) {
    ConnectionStreams server_conn = auth.getConnectionStreams();
    // Authenticates the user and establishes a connection to the server
    class Authentication extends Dialog implements ActionListener, KeyListener {
    // Object holding information relevant to the server connection
    ConnectionStreams server_conn;
    final static int port = 6012;
    // Authenticates the user and establishes connection to the server
    public Authentication(Frame parent) {
    // call the class Dialog's constructor
    super(parent, "User Authentication", true);
    setLocation(parent.getSize().width/3, parent.getSize().height/2);
    setupDialog();
    // sets up the components of the dialog box
    private void setupDialog() {
    // create and set the layout manager
    //Create a username text field here
    //Create a password text field here
    //Create a OK button here
    public void actionPerformed(ActionEvent e) {
    authenticateUser();
    dispose();
    // returns the ConnectionStreams object
    public ConnectionStreams getConnectionStreams() {
    return(server_conn);
    // authenticates the user
    private void authenticateUser() {
    Socket socket;
    InetAddress address;
    try {
    // open socket to server
    System.out.println("Ready to connect to server on: " + port);
    socket = new Socket("mugca.its.monash.edu.au", port);
    address = socket.getInetAddress();
    System.out.println("The hostname,address,hostaddress,localhost is:" + address.getHostName() + ";\n" +
    address.getAddress() + ";\n" +
    address.getHostAddress() + ";\n" +
    address.getLocalHost());
    catch(Exception e) {
    displayMessage("Error occured. See console");
    System.err.println(e);
                                  e.printStackTrace();
    }

    Hi, there:
    Thanks for the help. But I don't have to configure the security policy. Instead, inspired by a message in this forum, I simply upload the applet to the HTTP server (mugca.its.monash.edu.au) where my won server is running. Then the applet is download from the server and running fine in my local machine.
    Dengsheng

  • File transfer, read write through sockets in client server programming java

    Hello All, need help again.
    I am trying to create a Client server program, where, the Client first sends a file to Server, on accepting the file, the server generates another file(probably xml), send it to the client as a response, the client read the response xml, parse it and display some data. now I am successful sending the file to the server, but could not figure out how the server can create and send a xml file and send it to the client as response, please help. below are my codes for client and server
    Client side
    import java.io.BufferedInputStream;
    import java.io.BufferedOutputStream;
    import java.io.BufferedReader;
    import java.io.DataInputStream;
    import java.io.DataOutputStream;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileWriter;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.PrintWriter;
    import java.net.InetAddress;
    import java.net.Socket;
    import java.net.UnknownHostException;
    public class XMLSocketC
         public static void main(String[] args) throws IOException
              //Establish a connection to socket
              Socket toServer = null;
              String host = "127.0.0.1";     
              int port = 4444;
              try
                   toServer = new Socket(host, port);
                   } catch (UnknownHostException e) {
                System.err.println("Don't know about host: localhost.");
                System.exit(1);
            } catch (IOException e) {
                System.err.println("Couldn't get I/O for the connection to host.");
                System.exit(1);
              //Send file over Socket
            //===========================================================
            BufferedInputStream fileIn = null;
              BufferedOutputStream out = null;
              // File to be send over the socket.
              File file = new File("c:/xampp/htdocs/thesis/sensorList.php");
              // Checking for the file to be sent.
              if (!file.exists())
                   System.out.println("File doesn't exist");
                   System.exit(0);
              try
                   // InputStream to read the file
                   fileIn = new BufferedInputStream(new FileInputStream(file));
              }catch(IOException eee)
                   System.out.println("Problem, kunne ikke lage fil");
              try
                   InetAddress adressen = InetAddress.getByName(host);
                   try
                        System.out.println("Establishing Socket Connection");
                        // Opening Socket
                        Socket s = new Socket(adressen, port);
                        System.out.println("Socket is clear and available.....");
                        // OutputStream to socket
                        out = new BufferedOutputStream(s.getOutputStream());
                        byte[] buffer = new byte[1024];
                        int numRead;
                        //Checking if bytes available to read to the buffer.
                        while( (numRead = fileIn.read(buffer)) >= 0)
                             // Writes bytes to Output Stream from 0 to total number of bytes
                             out.write(buffer, 0, numRead);
                        // Flush - send file
                        out.flush();
                        // close OutputStream
                        out.close();
                        // close InputStrean
                        fileIn.close();
                   }catch (IOException e)
              }catch(UnknownHostException e)
                   System.err.println(e);
            //===========================================================
            //Retrieve data from Socket.
              //BufferedReader in = new BufferedReader(new InputStreamReader(toServer.getInputStream()));
              DataInputStream in = new DataInputStream(new BufferedInputStream(toServer.getInputStream()));
              //String fromServer;
            //Read from the server and prints.
              //Receive text from server
              FileWriter fr = null;
              String frn = "xxx_response.xml";
              try {
                   fr = new FileWriter(frn);
              } catch (IOException e1) {
                   // TODO Auto-generated catch block
                   e1.printStackTrace();
              try{
                   String line = in.readUTF();                    //.readLine();
                   System.out.println("Text received :" + line);
                   fr.write(line);
              } catch (IOException e){
                   System.out.println("Read failed");
                   System.exit(1);
            in.close();
            toServer.close();
    public class XMLSocketS
          public static void main(String[] args) throws IOException
              //Establish a connection to socket
               ServerSocket serverSocket = null;
                 try {
                     serverSocket = new ServerSocket(4444);
                 } catch (IOException e) {
                     System.err.println("Could not listen on port: 4444.");
                     System.exit(1);
              Socket clientLink = null;
              while (true)
                        try
                             clientLink = serverSocket.accept();
                           System.out.println("Server accepts");
                             BufferedInputStream inn = new BufferedInputStream(clientLink.getInputStream());
                             BufferedOutputStream ut = new BufferedOutputStream(new FileOutputStream(new File("c:/xampp/htdocs/received_from_client.txt")));
                             byte[] buff = new byte[1024];
                             int readMe;
                             while( (readMe = inn.read(buff)) >= 0)
                             {     //reads from input stream, writes the file to disk
                                  ut.write(buff, 0, readMe);
                             // close the link to client
                             clientLink.close();                         
                             // close InputStream
                             inn.close();                         
                             // flush
                             ut.flush();                         
                             // close OutputStream
                             ut.close();     
                             //Sending response to client     
                             //============================================================
                             //============================================================
                             System.out.println("File received");
              }catch(IOException ex)
              {System.out.println("Exception.");}
                        finally
                             try
                                  if (clientLink != null) clientLink.close();
                             }catch(IOException e) {}
                 clientLink.close();
                 //serverSocket.close();
    }

    SERVER
    import java.net.*;
    import java.io.*;
    public class XMLSocketS
          public static void main(String[] args) throws IOException
                   //Establish a connection to socket
               ServerSocket serverSocket = null;
                 try {
                     serverSocket = new ServerSocket(4545);
                 } catch (IOException e) {
                     System.err.println("Could not listen on port: 4444.");
                     System.exit(1);
              Socket clientLink = null;
                  try
                             clientLink = serverSocket.accept();
                         System.out.println("Server accepts the client request.....");
                         BufferedInputStream inn = new BufferedInputStream(clientLink.getInputStream());
                             BufferedOutputStream ut = new BufferedOutputStream(new FileOutputStream(new File("c:/xampp/htdocs/received_from_client.txt")));
                             byte[] buff = new byte[1024];
                             int readMe;
                             while( (readMe = inn.read(buff)) >= 0)
                             {     //reads from input stream, writes the file to disk
                                  ut.write(buff, 0, readMe);
                             ut.flush();                         
                             //Sending response to client     
                             //============================================================
                             BufferedInputStream ftoC = null;
                             BufferedOutputStream outtoC = null;
                             // File to be send over the socket.
                             File file = new File("c:/xampp/htdocs/thesis/user_registration_response.xml");
                             try
                                  // InputStream to read the file
                                   ftoC = new BufferedInputStream(new FileInputStream(file));
                             }catch(IOException eee)
                             {System.out.println("Problem reading file");}
                             // OutputStream to socket
                             outtoC = new BufferedOutputStream(clientLink.getOutputStream());
                             byte[] buffer = new byte[1024];
                             int noRead;
                             //Checking if bytes available to read to the buffer.
                             while( (noRead = ftoC.read(buffer)) >= 0)
                                  // Writes bytes to Output Stream from 0 to total number of bytes
                                  outtoC.write(buffer, 0, noRead);
                             outtoC.flush();
                             //============================================================
                             System.out.println("File received");
              }catch(IOException ex)
              {System.out.println("Exception.");}
                        finally
                             try
                                  if (clientLink != null) clientLink.close();
                             }catch(IOException e) {}
                 clientLink.close();
                 //serverSocket.close();
          }CLIENT SIDE
    import java.io.*;
    import java.net.*;
    public class XMLSocketC
              @SuppressWarnings("deprecation")
              public static void main(String[] args)
                   // Server: "localhost" here. And port to connect is 4545.
                   String host = "127.0.0.1";          
                   int port = 4545;
                   BufferedInputStream fileIn = null;
                   BufferedOutputStream out = null;
                   // File to be send over the socket.
                   File file = new File("c:/xampp/htdocs/thesis/sensorList.xml");
                   try
                        // InputStream to read the file
                        fileIn = new BufferedInputStream(new FileInputStream(file));
                   }catch(IOException eee)
                   {System.out.println("Problem");}
                   try
                             System.out.println("Establishing Socket Connection");
                             // Opening Socket
                             Socket clientSocket = new Socket(host, port);
                             System.out.println("Socket is clear and available.....");
                             // OutputStream to socket
                             out = new BufferedOutputStream(clientSocket.getOutputStream());
                             byte[] buffer = new byte[1024];
                             int numRead;
                             //Checking if bytes available to read to the buffer.
                             while( (numRead = fileIn.read(buffer)) >= 0)
                                  // Writes bytes to Output Stream from 0 to total number of bytes
                                  out.write(buffer, 0, numRead);
                             // Flush - send file
                             out.flush();
                             //=======================================
                             DataInputStream in = new DataInputStream(new BufferedInputStream(clientSocket.getInputStream()));
                             BufferedWriter outf = new BufferedWriter(new FileWriter("c:/xampp/htdocs/received_from_server.txt",true));
                             String str;
                             while(!(str = in.readLine()).equals("EOF")) {     
                                  System.out.println("client : Read line -> <" + str + ">");
                                  outf.write(str);//Write out a string to the file
                                  outf.newLine();//write a new line to the file (for better format)
                                  outf.flush();
                             //=======================================
                             // close OutputStream
                             out.close();
                             // close InputStrean
                             fileIn.close();
                             // close Socket
                             clientSocket.close();
                        }catch (IOException e)
                        {System.out.println("Exception.");}
         Could you please point where am I doing the stupid mistake, client to server is working properly, but the opposite direction is not.
    Thanks

  • Client/server socket based application

    hi does anyone have example of client/server socket based application using Spring and Maven
    where application do the following
    Client sends a request with a path to any file on the server
    „h Server reads the file and responds back with the content
    „h Client outputs the content to the console
    am trying to follow this
    http://www2.sys-con.com/itsg/virtualcd/java/archives/0205/dibella/index.html
    http://syntx.io/a-client-server-application-using-socket-programming-in-java/
    am using java 6

    i have attempt code but i wht to do the following
    client/server socket based application that will read the content of a file and stream the content of the file to the client. The client must simply output the content of the file to the console using System.out. The client must be able to run in a standalone mode (non-network mode) or in a remote mode.
    Additionally the client must be designed in a way that i can print the output to a console but must be interchangeable where if requirements change i can persist the response to file or persist the response to a database.
    /* Server.java*/
    ///ifgetBoolen= true then...
    import java.io.*;
    import java.net.*;
    import java.util.*;
    import java.sql.*;
    public class Server
        static String array[][];
        // STEP 1 a1  
        // Server socket
        ServerSocket listener;
        // STEP 1 a2 Client connection
        Socket client;
        ObjectInputStream in;
        ObjectOutputStream out;
        public void createConnection() throws IOException
                System.out.println("\nSERVER >>> Waiting for connection.....");
                client = listener.accept();
                String IPAddress = "" + client.getInetAddress();
                DisplayMessage("SERVER >>> Connected to " + IPAddress.substring(1,IPAddress.length()));
          public void runServer()
            // Start listening for client connections
            // STEP 2
            try
                listener = new ServerSocket(12345, 10);
                createConnection();
                  // STEP 3
    //              processConnection();
            catch(IOException ioe)
                DisplayMessage("SERVER >>> Error trying to listen: " + ioe.getMessage());
        private void closeConnection()
            DisplayMessage("SERVER >>> Terminating connections");
            try
                if(out != null && in != null)
                      out.close();
                    in.close();
                    client.close();                
            catch(IOException ioe)
                DisplayMessage("SERVER >>> Closing connections");
        public static void define2DArray(ResultSet RS, int Size)
            try
                ResultSetMetaData RMSD = RS.getMetaData();
                DisplayMessage("SERVER >>> Requested arraySize: " + Size);
                if (RS.next())
                    array = new String[Size][RMSD.getColumnCount()];
                    for (int Row = 0; Row < Size; Row++)
                        for (int Col = 0; Col < RMSD.getColumnCount(); Col++)
                            array[Row][Col] = new String();
                            array[Row][Col] = RS.getString(Col+1);
                            DisplayMessage(array[Row][Col] + " ");
                        RS.next();
                else
                    array = new String[1][1];
                    array[0][0] = "#No Records";
            catch (Exception e)
                DisplayMessage("SERVER >>> Error in defining a 2DArray: " + e.getMessage());  
        public static void DisplayMessage(final String IncomingSMS)
            System.out.println(IncomingSMS);
    //client
    * @author
    import java.io.*;
    import java.net.*;
    import javax.swing.*;
    public class ClientSystem
        static Socket server;
        static ObjectOutputStream out;
        static ObjectInputStream in;
        static String Response[][];
        static boolean IsConnected = false;
        static int Num = 0;
        public static void connectToServer() throws IOException
            server = new Socket("127.0.0.1", 12345);
    //        server = new Socket("000.00.98.00", 12345);
            String IPAddress = "" + server.getInetAddress();
            DisplayMessage("\nCLIENT >>> Connected to " + IPAddress.substring(1,IPAddress.length()));
        public static void getStreams() throws IOException
            out = new ObjectOutputStream(server.getOutputStream());
            out.flush();
              in = new ObjectInputStream(server.getInputStream());
              IsConnected = true;
              DisplayMessage("CLIENT >>> Got I/O streams");  
        public static void runClient()
            try
                connectToServer();
                getStreams();
                  DisplayMessage("CLIENT >>> Connection successfull....\n");
                  DisplayMessage("CLIENT >>> Want to talk to server");
            catch (IOException ioe)
                System.out.print("."+Num);
                Num++;
        public static void closeConnection()
            try
                out.close();
                in.close();
                server.close();  
            catch(IOException error)
                DisplayMessage("CLIENT >>> Could not close connections");
        public static void Start()
            System.out.print("\nCLIENT >>> Attempting connection.....");
            try
                IsConnected = false;
                while (IsConnected == false)
                    runClient();
                    if (IsConnected == false)
                        Thread.sleep(100);
            catch (Exception e)
                DisplayMessage("CLIENT >>> Attempting connection.....");
        public static String sendSMS(String sms)
            Response = new String[0][0];
            try
                DisplayMessage("CLIENT >>> " + sms);
                out.writeObject(sms);
                out.flush();
                Response = (String[][])in.readObject();
                DisplayMessage("CLIENT >>> Waiting for server to respond...");
                for (int Row = 0; Row < Response.length; Row++)
                    System.out.printf( "_SERVER >>> \t");
                    for (int Col = 0; Col < Response[Row].length; Col++)
                        //DisplayMessage( "_SERVER >>> " + Response[Row][Col] + " ");
                        System.out.printf( "%s\t", Response[Row][Col]);
                    System.out.println();
                DisplayMessage("CLIENT >>> Query processed successfully....\n");
            catch(ClassNotFoundException cnfe)
                DisplayMessage("CLIENT >>> Class not found for casting received object");
            catch(IOException ioe)
                reConnect();          
            catch (Exception sqle)
                DisplayMessage("CLIENT >>> Error sending query ??? " + sqle.getMessage());
            return "transmission successfull";
        public static void reConnect()
            try
                DisplayMessage("CLIENT >>> Connection was lost. Trying to reconnect...");
                closeConnection();
                Thread.sleep(100);
                IsConnected = false;
                while (IsConnected == false)
                    runClient();
                    Thread.sleep(200);
            catch (Exception e)
                DisplayMessage("CLIENT >>> Error trying to Re-Connect...");
        public static void DisplayMessage(final String IncomingSms)
            System.out.println(IncomingSms);
        System.out.printf("Isms: %s", IncomingSms);  ///naah.
        public static String[][] getResponse()
            return Response;
        public static String getResponse(int row, int col)
            return Response[row][col];
    how can i do below using above code
    The program must be able to work in a non-networked mode. In this mode, the server and client must run in the same VM and must perform no networking, must not use loopback networking i.e: no “localhost” or “127.0.0.1”, and must not involve the serialization of any objects when communicating between the client and server components.
    The operating mode is selected using the single command line argument that is permitted.
    imust use a socket connection and define a protocol. networking must be entirely bypassed in the non-network mode.

  • Are there any Client/Server Application (using sockets) design patterns?

    Hi,
    The title of the post nearly says it all. I am searching for different design patterns related with the development of a client/server application. I understand that there must be any different ways on how a client/server application can be developed.
    Regards,
    Sim085
    Disclaimer:
    When I enter in the Socket forum on this site I recieve this message "Thank you for any participation in this forum. Due to a lack of relevant activity, we have decided to archive this forum on June 16, 2006. For future posts on this topic, we suggest you use the Networking forum" and I am not allowed to create a new post! However I can see posts done yesterday! All i did is add the forum in 'my forums'. Does this happen to you people as well?

    Hi Sim085...How are you?
    So look this:
    http://forum.java.sun.com/thread.jspa?threadID=5148926&tstart=75
    I don�t know if is what you want...but I hope in this^^
    Ok man...If you have one example for help you is better.
    [ ]

  • Client Server Socket With GUI

    Hi,
    As the name of the forum suggests I am very new to this whole thing.
    I am trying to write a client/server socket program that can encrypt and decrypt and has a GUI, can't use JCE or SSL or any built in encryption tools.
    I have the code for everything cept the encryption part.
    Any help, greatly appreciated,

    tnks a million but how do i incorporate that into the following client and server code:
    here's the client code:
    import java.awt.Color;
    import java.awt.BorderLayout;
    import java.awt.event.*;
    import javax.swing.*;
    import java.io.*;
    import java.net.*;
    class SocketClient extends JFrame
              implements ActionListener {
    JLabel text, clicked;
    JButton button;
    JPanel panel;
    JTextField textField;
    Socket socket = null;
    PrintWriter out = null;
    BufferedReader in = null;
    SocketClient(){ //Begin Constructor
    text = new JLabel("Text to send over socket:");
    textField = new JTextField(20);
    button = new JButton("Click Me");
    button.addActionListener(this);
    panel = new JPanel();
    panel.setLayout(new BorderLayout());
    panel.setBackground(Color.white);
    getContentPane().add(panel);
    panel.add("North", text);
    panel.add("Center", textField);
    panel.add("South", button);
    } //End Constructor
    public void actionPerformed(ActionEvent event){
    Object source = event.getSource();
    if(source == button){
    //Send data over socket
    String text = textField.getText();
    out.println(text);
         textField.setText(new String(""));
    //Receive text from server
    try{
         String line = in.readLine();
    System.out.println("Text received :" + line);
    } catch (IOException e){
         System.out.println("Read failed");
         System.exit(1);
    public void listenSocket(){
    //Create socket connection
    try{
    socket = new Socket("HUGHESAN", 4444);
    out = new PrintWriter(socket.getOutputStream(), true);
    in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    } catch (UnknownHostException e) {
    System.out.println("Unknown host: HUGHESAN.eng");
    System.exit(1);
    } catch (IOException e) {
    System.out.println("No I/O");
    System.exit(1);
    public static void main(String[] args){
    SocketClient frame = new SocketClient();
         frame.setTitle("Client Program");
    WindowListener l = new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
    System.exit(0);
    frame.addWindowListener(l);
    frame.pack();
    frame.setVisible(true);
         frame.listenSocket();
    SERVER Code
    import java.awt.Color;
    import java.awt.BorderLayout;
    import java.awt.event.*;
    import javax.swing.*;
    import java.io.*;
    import java.net.*;
    class SocketServer extends JFrame
              implements ActionListener {
    JButton button;
    JLabel label = new JLabel("Text received over socket:");
    JPanel panel;
    JTextArea textArea = new JTextArea();
    ServerSocket server = null;
    Socket client = null;
    BufferedReader in = null;
    PrintWriter out = null;
    String line;
    SocketServer(){ //Begin Constructor
    button = new JButton("Click Me");
    button.addActionListener(this);
    panel = new JPanel();
    panel.setLayout(new BorderLayout());
    panel.setBackground(Color.white);
    getContentPane().add(panel);
    panel.add("North", label);
    panel.add("Center", textArea);
    panel.add("South", button);
    } //End Constructor
    public void actionPerformed(ActionEvent event) {
    Object source = event.getSource();
    if(source == button){
    textArea.setText(line);
    public void listenSocket(){
    try{
    server = new ServerSocket(4444);
    } catch (IOException e) {
    System.out.println("Could not listen on port 4444");
    System.exit(-1);
    try{
    client = server.accept();
    } catch (IOException e) {
    System.out.println("Accept failed: 4444");
    System.exit(-1);
    try{
    in = new BufferedReader(new InputStreamReader(client.getInputStream()));
    out = new PrintWriter(client.getOutputStream(), true);
    } catch (IOException e) {
    System.out.println("Accept failed: 4444");
    System.exit(-1);
    while(true){
    try{
    line = in.readLine();
    //Send data back to client
    out.println(line);
    } catch (IOException e) {
    System.out.println("Read failed");
    System.exit(-1);
    protected void finalize(){
    //Clean up
    try{
    in.close();
    out.close();
    server.close();
    } catch (IOException e) {
    System.out.println("Could not close.");
    System.exit(-1);
    public static void main(String[] args){
    SocketServer frame = new SocketServer();
         frame.setTitle("Server Program");
    WindowListener l = new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
    System.exit(0);
    frame.addWindowListener(l);
    frame.pack();
    frame.setVisible(true);
         frame.listenSocket();
    Again help on this is very welcomed

  • Client/server application using sockets

    Hi there,
    I'm trying to create a client/server application using sockets where the client has a GUI of a membership application form for some sort of club. Basically, the user will enter their name, address, membership no. etc in to various Jtext fields and then press a JButton to submit these details to the server. The server will then hopefully just dump these details to a text file.
    Can anyone give me any examples, ideas on how to start, links etc.
    Thanks v. much in anticipation,
    Nick

    Take a browse of the tutorial on sockets: http://java.sun.com/docs/books/tutorial/networking/sockets/clientServer.html

  • Client / Server Socket Communication - Should use 2 ports?

    If we have a client server architecture using a socket based connection, should there be 2 serperate sockets? One dedicated to sending and one dedictated to receiving? What happens if both the client and server both send at the same time? How does that get handled? Does one of the messages get dropped? Thanks...

    There are of course reasons you might want to use two sockets.
    For instance security. One socket is encrypted and the other isn't. Or because the server initiates a confirmed port connection back it verifies the IP.
    Or because the main socket is used for control and the second one is used for data. That way the client can tell the server to pause or make other adjustments in the data while the data is still flowing.

Maybe you are looking for