首页 > 代码库 > 网络编程--Socket与ServerSocket

网络编程--Socket与ServerSocket

1、服务器端代码

package net;

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

public class Server {
    public static void main(String[] args) throws Exception{
        ServerSocket server =  new ServerSocket(8888);
        System.out.println("等待客户端连接.......");
        Socket client = server.accept(); //接收客户端连接
        
        PrintStream out = new PrintStream(client.getOutputStream());
        out.println("HelloWorld"); //要输出的信息
        out.close();
        client.close();
        server.close();
    }
}

运行程序,控制台输出:   等待客户端连接.......
2、客户端代码

package net;

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

public class Client {
    
    public static void main(String[] args) throws Exception {
        Socket client = new Socket("localhost", 8888);
        Scanner scan = new Scanner(client.getInputStream());
        scan.useDelimiter("\n");
        if(scan.hasNext()){
            System.out.println(scan.next());
        }
        scan.close();
        client.close();
    }

}

运行程序,控制台输出: HelloWorld(如果服务器端程序停止运行,则客户端无信息输出)

网络编程--Socket与ServerSocket