Aquí, vamos a ver el enfoque de conexión al socket 6123.
Acercarse:
- Cree un objeto de la clase Socket y pase 6123 como argumento.
- Acepte conexiones con el método accept() de la clase ServerSocket.
- Obtenga la dirección de la conexión con el método getInetAddress() de la clase Socket y getHostAddress() de la clase InetAddress .
Código del servidor:
Java
// Make a server to allow the connection to the socket 6123 import java.io.IOException; import java.net.InetAddress; import java.net.ServerSocket; import java.net.Socket; public class Server { public static void main(String[] args) { check(); } private static void check() { try { // Creating object of ServerSocket class ServerSocket connection = new ServerSocket(6123); while (true) { System.out.println("Listening"); // Creating object of Socket class Socket socket = connection.accept(); // Creating object of InetAddress class InetAddress address = socket.getInetAddress(); System.out.println( "Connection made to " + address.getHostAddress()); pause(1000); // close the socket socket.close(); } } catch (IOException e) { System.out.println("Exception detected: " + e); } } private static void pause(int ms) { try { Thread.sleep(ms); } catch (InterruptedException e) { } } }
Producción
Codigo del cliente:
Java
// A Java program for a Client import java.net.*; import java.io.*; public class Client { // initialize socket and input output streams private Socket socket = null; private DataInputStream input = null; private DataOutputStream out = null; // constructor to put ip address and port public Client(String address, int port) { // establish a connection try { socket = new Socket(address, port); System.out.println("Connected"); // takes input from terminal input = new DataInputStream(System.in); // sends output to the socket out = new DataOutputStream( socket.getOutputStream()); } catch (UnknownHostException u) { System.out.println(u); } catch (IOException i) { System.out.println(i); } // string to read message from input String line = ""; // keep reading until "Over" is input while (!line.equals("Over")) { try { line = input.readLine(); out.writeUTF(line); } catch (IOException i) { System.out.println(i); } } // close the connection try { input.close(); out.close(); socket.close(); } catch (IOException i) { System.out.println(i); } } public static void main(String args[]) { Client client = new Client("127.0.0.1", 6123); } }
Producción