实现功能:服务端和客户端能相互发送消息。
服务端:
package com.javasocket;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
public Server() {
try {
ServerSocket serverSocket = new ServerSocket(10000);
Socket socket = serverSocket.accept();
String remoteIP = serverSocket.getInetAddress().getHostAddress();
String remotePort = ":" + serverSocket.getLocalPort();
System.out.println("Aclientcome in ! IP : " + remoteIP + remotePort);
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String readerLine = br.readLine();
System.out.println(readerLine);
PrintWriter pw = new PrintWriter(socket.getOutputStream(), true);
pw.println("Your Message Received !");
pw.close();
br.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
new Server();
}
}
客户端:
package com.javasocket;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
public class Client {
public Client() {
try {
Socket socket = new Socket("127.0.0.1", 10000);
BufferedReader readCMD = new BufferedReader(new InputStreamReader(System.in));
PrintWriter pw = new PrintWriter(socket.getOutputStream(), true);
pw.println(readCMD.readLine());
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
System.out.println(br.readLine());
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
new Client();
}
}