TCP发送消息(Java)

将客户端发送的消息传递给服务器端,逆转后输出

客户端:

import java.io.*;
import java.net.Socket;
import java.util.Scanner;

/**
 * Created by Administrator on 2020/6/30.
 */
public class socket01 {
    public static void main(String[] args) throws IOException {
        Scanner sc = new Scanner(System.in);
        Socket socket = new Socket("127.0.0.1",54321);

        BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));  //输入流
        PrintStream ps = new PrintStream(socket.getOutputStream());  //输出流

        ps.println(sc.nextLine());
        System.out.println(br.readLine());
    }
}

服务器端:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * Created by Administrator on 2020/6/30.
 */
public class socket02 {
    public static void main(String[] args) throws IOException {
        ServerSocket server=new ServerSocket(54321);
        System.out.println("服务器启动");

        while (true){
            Socket socket = server.accept();

            new Thread(){
                public void run(){
                    try {
                        BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));  //输入流
                        PrintStream ps = new PrintStream(socket.getOutputStream());  //输出流

                        String line = br.readLine();
                        line = new StringBuilder(line).reverse().toString();
                        ps.println(line);
                        socket.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                }
            }.start();
        }
    }
}

 

你可能感兴趣的:(Java学习)