In an earlier post, I have discussed how to implement socket communication with python. I recently was asked to implement similar functions, but in Java. Here is how I did that.
- Create a new Java project, let’s name it JSocketClient;
- Create another Java project, let’s name it JSocketServer;
- In both projects, create an App class, and add a static Main function respectively:
- In the Client project, add a class JSocketClient:
- In the server project, add a class JSocketServer:
private Socket _client;
private String _ServerName = “localhost”;
private int _port = 8089;
_client = new Socket(_ServerName, _port);
public void SendString(String data) { if (_client == null) { System.out.println(“Client:\tEmpty Socket client. Please retry”); return; } OutputStream oStream; try { System.out.println(“Client:\tSending data:” + data); oStream = _client.getOutputStream(); DataOutputStream out = new DataOutputStream(oStream); out.writeUTF(data); } catch (IOException e) { e.printStackTrace(); } } |
import java.io.DataInputStream; public class JSocketServer extends Thread { public void run() { |
- Run the server project, where in the main() function:
public class App {
public static void main(String[] args) {
JSocketServer t = new JSocketServer(8089);
t.start();
}
} - Run the client project, where in the main() function:
public class App {
static JSocketClient client;
public static void main(String[] args) {
client=new JSocketClient();
}
}
That is it! Now let’s see the result in console of Eclipse:
That is it. Happy coding.
Filed under: Java, Programming Tagged: example, how to, java, Socket, tutorial
