I want to create a Client/Server application on java, server with an IP address 192.168.1.100 waiting for a client request on port 4500.
the client reads the string from the keyboard, sends a connection request to the server. once the connection is established, it sends the string to the server.
this is the code I tried :
for Serveur:
import java.net.*;
import java.io.*;
public class Serveur {
public Serveur() {
// TODO Auto-generated constructor stub
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
try
{
ServerSocket ecoute;
ecoute = new ServerSocket(1111);
Socket service = null;
System.out.println("Serveur en attente d'un client !");
while(true)
{
service = ecoute.accept();
System.out.println("Client connécté !");
DataInputStream is = new DataInputStream(service.getInputStream());
System.out.println("Client dit : " + is.readUTF().toUpperCase());
service.close();
}
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
for client :
import java.net.*;
import java.io.*;
import java.util.Scanner;
public class Client {
public Client() {
// TODO Auto-generated constructor stub
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("Connexion en cours ...");
try {
Socket s = new Socket("localhost", 1111);
DataOutputStream os = new DataOutputStream(s.getOutputStream());
Scanner sn = new Scanner(System.in);
os.writeUTF(sn.nextLine());
} catch ( IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Connécté au serveur !");
}
}
but I had a problem with this code :
java.net.ConnectException: Connection timed out: connect at java.net.DualStackPlainSocketImpl.connect0(Native Method) at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source) at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source) at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source) at java.net.AbstractPlainSocketImpl.connect(Unknown Source) at java.net.PlainSocketImpl.connect(Unknown Source) at java.net.SocksSocketImpl.connect(Unknown Source) at java.net.Socket.connect(Unknown Source) at java.net.Socket.connect(Unknown Source) at java.net.Socket.(Unknown Source) at java.net.Socket.(Unknown Source) at Client.main(Client.java:18)