Socket -2 realizes simple communication of socket

Requirements: Create a client that sends data to the server

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();
}

}

2.Server2
/** * Create a server to receive  * information
 sent by a client  */ public class Server { /* * Attribute: server, used to specify the port number of the server */ private ServerSocket server; public Server (){ try { //Specify the port number of the server server = new ServerSocket(8088); } catch (Exception e) { e.printStackTrace(); } } public void start(){ try { /* * Call the blocking method, To listen to the client, get the *Socket socket object. */ System.out.println("--waiting for connection--"); Socket socket = server.accept(); System.out.println("--connection successful--");  // Get through socket Input stream object InputStream is = socket.getInputStream(); BufferedReader br = 























 
 


new BufferedReader(
new InputStreamReader(is));
String line = ""; while((line=br.readLine())!=null){ System.out.println("Server: "+line); } } catch (Exception e) { e.printStackTrace(); } } public static void main(String[] args) { Server server = new Server(); server.start();  // Address is already use:jvm_bind; } } 3 .As a result     , run the server first and wait for the connection, then run the client - enter the information, press Enter, and the message from the client to the server appears.











 




                      



Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325505825&siteId=291194637