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:

karse said...

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!

Erik said...

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.

karse said...

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!

karse said...

Hi again,

I've solved the problem replacing the

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

by

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

Thank you!

Kswarna said...

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

Erik said...

hello Saqib Atiq,

Thanks for your input:)

Unknown said...

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!

Unknown said...

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?

oearias said...

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!

Unknown said...

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

Unknown said...
This comment has been removed by the author.
James Anderson said...

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

Moubarak said...

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

Unknown said...

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

Gary said...

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

Alex said...

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

Anonymous said...

Server is running on computer but string is not receivd on emulator but vice versa is running successful

Unknown said...

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

Unknown said...

Hey,

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

Erik said...

Hello Omkar Chavan,

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

Unknown said...

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???

Erik said...

hello sm deepak,

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