前面我们讲了基于UDP的网络编程
下面我们来讲基于TCP的回显服务编写
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
public class Server {
private static ServerSocket socket = null;
public Server(int port) throws IOException {
socket = new ServerSocket(port);
}
public static void start() throws IOException {
System.out.println("服务器端启动!");
//使用多线程的方式,可以与多个客户端连接
while (true){
Socket clientSocket = socket.accept();
Thread thread = new Thread(()->{
try {
procession(clientSocket);
} catch (IOException e) {
throw new RuntimeException(e);
}
});
thread.start();
}
}
public static void procession(Socket clientSocket) throws IOException {
System.out.printf("[%s:%d] 客户端上线!",clientSocket.getInetAddress(),clientSocket.getPort());
System.out.println();
//TCP使用的是I/O流
try (InputStream inputStream = clientSocket.getInputStream();
OutputStream outputStream = clientSocket.getOutputStream();)
{
while (true){
Scanner scanner = new Scanner(inputStream);
if (!scanner.hasNext()){
System.out.printf("[%s:%d] 客户端下线",clientSocket.getInetAddress(),clientSocket.getPort());
System.out.println();
break;
}
String request = scanner.next();
String response = process(request);
PrintWriter writer = new PrintWriter(outputStream);
writer.println(response);
writer.flush();
System.out.printf("[%s:%d] req:%s,resp:%s",clientSocket.getInetAddress().toString(),clientSocket.getPort(),request,response);
System.out.println();
}
}catch (IOException e){
e.printStackTrace();
}finally {
try {
clientSocket.close();
}catch (IOException e){
e.printStackTrace();
}
}
}
public static String process(String request){
return request;
}
public static void main(String[] args) throws IOException {
Server server = new Server(9090);
server.start();
}
}
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;
public class Client {
public static Socket socket = null;
public Client(String ip,int port) throws IOException {
socket = new Socket(ip,port);
}
public static void start() throws IOException {
System.out.println("客户端启动!");
Scanner scanner = new Scanner(System.in);
try (InputStream inputStream = socket.getInputStream();
OutputStream outputStream = socket.getOutputStream()){
PrintWriter writer = new PrintWriter(outputStream);
Scanner scannerRes = new Scanner(inputStream);
while (true){
System.out.print("->");
String request = scanner.next();
writer.println(request);
writer.flush();
String response = scannerRes.next();
System.out.println(response);
}
}catch (IOException e){
e.printStackTrace();
}
}
public static void main(String[] args) throws IOException {
Client client = new Client("127.0.0.1",9090);
client.start();
}
}
最终结果
?
?
?
?