Java学习之路-NET-Socket简单例子

利用Socket, 在服务器端编程发送数据, 客户端接受该数据
package cn.antraces.NET;

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 SocketTest implements Runnable{

    @Override
    public void run() { //由于调用了accept, 所以将服务端放入单独的线程
        try {
            server();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public SocketTest(){
        Thread th = new Thread(this);
        th.start();
        try {
            client();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void server() throws IOException {
        ServerSocket serverSocket = new ServerSocket(23333);
        Socket socket = serverSocket.accept();  //调用accept阻塞,等待客户端连接。
        PrintWriter printWriter = new PrintWriter(socket.getOutputStream(), true);
        printWriter.println("Hello, world!"); //向客户端发送 "Hello, world!"
        socket.close();
        serverSocket.close();
    }

    public static void client() throws IOException {
        Socket socket = new Socket("127.0.0.1",23333);
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        System.out.println(bufferedReader.readLine());
        bufferedReader.close();
        socket.close();
    }

    public static void main (String[] args){
        new SocketTest();
    }
}
按讚

發佈留言

電子郵件地址不會被公開。必填項已用 * 標註