Thursday, January 13, 2011

Implement a simple Socket Server in Eclipse

Implement a simple Socket Server in Eclipse

In last exercise "Simple communication using java.net.Socket", a simple client app have be implemented. Here I will implement the a simple Socket Server in Eclipse.

- In Eclipse, start a normal Java project.

- Create a new class, say MyServer.java in my case.
MyServer.java
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;


public class MyServer {
 
 public static void main(String[] args){
  ServerSocket serverSocket = null;
  Socket socket = null;
  DataInputStream dataInputStream = null;
  DataOutputStream dataOutputStream = null;
  
  try {
   serverSocket = new ServerSocket(8888);
   System.out.println("Listening :8888");
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  
  while(true){
   try {
    socket = serverSocket.accept();
    dataInputStream = new DataInputStream(socket.getInputStream());
    dataOutputStream = new DataOutputStream(socket.getOutputStream());
    System.out.println("ip: " + socket.getInetAddress());
    System.out.println("message: " + dataInputStream.readUTF());
    dataOutputStream.writeUTF("Hello!");
   } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
   finally{
    if( socket!= null){
     try {
      socket.close();
     } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
     }
    }
    
    if( dataInputStream!= null){
     try {
      dataInputStream.close();
     } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
     }
    }
    
    if( dataOutputStream!= null){
     try {
      dataOutputStream.close();
     } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
     }
    }
   }
  }
 }
}


- Now you can run the server by clicking the Run (Green arrow) button.



- If the app of last exercise is running at the same time, this Socket Server and the Client App can communicate with each other.

(Remember to check your ip and update in "Simple communication using java.net.Socket".)


download filesDownload the files.

22 comments:

  1. Hi, this is a very good tutorial and helped me a lot. I have only one question, how to display in the android client which is written instead of "hello"? I tried to pass the inputStream into the dataOutputStream.writeUTF but that crashes. I've tried several ways but I can't find the way to go. Can you help me? Thanks!

    ReplyDelete
  2. hello karse,

    I tried this ok:
    String dataStream = dataInputStream.readUTF();
    System.out.println("message: " + dataStream);
    //dataOutputStream.writeUTF("Hello!");
    dataOutputStream.writeUTF(dataStream);


    Have to quit and restart eclipse before re-try? the exercise program haven't close the server.

    ReplyDelete
    Replies
    1. Server is running on computer but string is not receivd on emulator but vice versa is running successful

      Delete
  3. Yes, I've tried to do the same that you wrote before but it doesn't work for me. It seems that the application crashes when I declare a String with the content of dataInputStream.readUTF() but don't crashes if I declare like String str = "hello";

    This is the code ...

    serverSocket.accept socket = ();
    DataInputStream = new DataInputStream (socket.getInputStream ());
    DataOutputStream = new DataOutputStream (socket.getOutputStream ());
    DataStream = dataInputStream.readUTF String ();
    System.out.println ("ip:" + socket.getInetAddress ());
    System.out.println ("message:" + dataInputStream.readUTF ());
    dataOutputStream.writeUTF (DataStream);

    The server comes to show this on console:

    Listening: 8888
    IP: / 192.168.1.38

    And from there the application crashes and asks for a forced closure. I do'ot know what happens, it seems that enters IOException ...

    Thanks for responding!

    ReplyDelete
  4. Hi again,

    I've solved the problem replacing the

    System.out.println("message: " + dataInputStream.readUTF());

    by

    System.out.println("message: " + dataStream);

    Thank you!

    ReplyDelete
  5. Hi,

    Thank you for the example. I am trying to run a server in Android with the client on my PC (Closed , tightly coupled N/W). Can I just switch the code and will it work? What would I need to do for this?

    Thanks,
    Karthik

    ReplyDelete
  6. hello Saqib Atiq,

    Thanks for your input:)

    ReplyDelete
  7. Hello, I was wondering if there was a way that the server (in this case it's the PC) can also send back a message to the client (Android device) and display it on the client's screen. I might of missed something if that was already discussed, but if not, then how do I do it? Thank you! This tutorial is exactly what I needed!

    ReplyDelete
  8. Hi Android-Er.
    My app isn't working: I didn't have 'IP: / 192.168.1.38' in my console and I kept getting this 'SocketTimeoutException'. Can you help me with it?

    ReplyDelete
  9. Hi, im trying to make a simple server in Android but i cant to do it, may i put The code here??? I need your help please!

    ReplyDelete
  10. Hi, from emulator to PC is everything ok, but from Android device to PC is not functional for me. IP links to your router or you PC? Thank you. David

    ReplyDelete
  11. This comment has been removed by the author.

    ReplyDelete
  12. Thanks for the code.
    How do i store the received data in a string variable?
    Please help!!!!!!!

    ReplyDelete
  13. hi i try to send different type of data like writeBytes and crash when i send that data

    ReplyDelete
  14. hello, this is a great tutorial. i tried and success. but i have tcp listener (server side) using .NET and i changed java server with .NET server.

    i've tried sending data using android but on server side which is use .NET get no result..
    can you help me?.. thanks

    ReplyDelete
  15. Hi, this doesn't work for me, I'm very new to android so excuse my ignorance. I've created the client within and android project and the server within a java project. I run the server first and then start the client, the app opens alright with the edit text and the button, the server print to the console "Listening: 8888" but after that theres no further output in the console, there's if I type something into the edit text field and hit send there's no action taken. My ip is correct and I even tried changing port numbers, the numbers are the same in both server and client.

    Any help here would be greatly appreciated.

    Regards,
    Gary

    ReplyDelete
  16. Hello,

    Great tutorial first off really helped me understand. I'm doing a project where the client is android and the server is android and it is routing through a mesh network.

    I'm thinking that this code could help me do this as long as both the client and server can connect to the mesh?

    Thank-you

    ReplyDelete
  17. I am receiving this error after opening the download file and putting it into a new project "Resource leak: 'serverSocket' is never closed"

    I don't know what it means, nor do I know how to fix it. It appears at this line
    "serverSocket = new ServerSocket(8888);"

    Thamls

    ReplyDelete
  18. Hey,

    how are both these devices connected. Are they in LAN or through internet. I want to do same using WIFI. Can you help.

    ReplyDelete
  19. Hello Omkar Chavan,

    both PC and android connect to the same router. PC use LAN cable, Android use WiFi.

    ReplyDelete
  20. Is it possible to connect through WAN connection??...
    I mean, I want to send text from My location 2 ma frnd's Destination (USA)..
    possible???

    ReplyDelete
  21. hello sm deepak,

    I haven't test it in such condition. Suppose it can, depends on your network setting.

    ReplyDelete