Requirements: Create a client that sends data to the server
private Socket socket;
public Client(){
try {
socket = new Socket("localhost",8088);
} catch (Exception e) {
e.printStackTrace();
}
}
/** The method for the client to start working
public void start(){
try {
/*
* Get the output stream through the Socket object,
* send the data to the server
*/ OutputStream os = socket.getOutputStream(); PrintWriter pw = new PrintWriter ( new OutputStreamWriter(os)) ; Scanner scan = new Scanner(System.in); while(true){ String input = scan.next(); pw.println(input); pw.flush(); } } catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
Client client = new Client();
client.start();
}
2.Server2
1.Client2:
public class Client {
/*Attribute: Socket, specify the IP and port of the server */private Socket socket;
public Client(){
try {
socket = new Socket("localhost",8088);
} catch (Exception e) {
e.printStackTrace();
}
}
/** The method for the client to start working
public void start(){
try {
/*
* Get the output stream through the Socket object,
* send the data to the server
*/ OutputStream os = socket.getOutputStream(); PrintWriter pw = new PrintWriter ( new OutputStreamWriter(os)) ; Scanner scan = new Scanner(System.in); while(true){ String input = scan.next(); pw.println(input); pw.flush(); } } catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
Client client = new Client();
client.start();
}
}