java网络编程,编写客户端和服务端的socket程序,客户端向服务端发送字符串“Hello”,服务端将收到字符串打印到控制台。

编写客户端和服务端的插口程序,客户端向服务端发送字符串“你好”,服务端将收到字符串打印到控制台。

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

public class Test {

    private static class Server extends Thread {
        @Override
        public void run() {
            ServerSocket ss = null;
            try {
                ss = new ServerSocket(8888);
                Socket s = ss.accept(); //实例化Socket对象,阻塞等待连接
                BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
                System.out.println(br.readLine());
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    ss.close();
                } catch (Exception e2) {
                }
            }

        }
    }

    private static class Client extends Thread {
        @Override
        public void run() {
            try {
                Socket s = new Socket("localhost", 8888);
                PrintStream ps = new PrintStream(s.getOutputStream());
                ps.println("hello");
                s.close();
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }

    public static void main(String[] args) {
        new Server().start();//启动服务
        try {
            Thread.sleep(1000);
        } catch (Exception e) {
        }
        new Client().start();
    }
}

 

你可能感兴趣的:(java)