首页 > 代码库 > ServerSocket 和 ClientSocket (网络编程)

ServerSocket 和 ClientSocket (网络编程)

TestServerSocket.java

package com.sxt.net;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

/*
 * 服务端
 */
public class TestServerSocket {
    public static void main(String[] args) throws IOException {
        System.out.println("服务端准备就绪");
        //服务端
        ServerSocket server = new ServerSocket(8888);
        //获取客户端的Socket
        Socket accept = server.accept();
        //获取客户端的输入流
        InputStream inputStream = accept.getInputStream();
        DataInputStream dis = new DataInputStream(inputStream);
        //输入流读取到程序中
        String readUTF = dis.readUTF();
        //客户端信息显示在控制台
        System.out.println(readUTF);
        
        //通过输出流发送数据回应客户端
        OutputStream outputStream = accept.getOutputStream();
        DataOutputStream dos = new DataOutputStream(outputStream);
        //输出流写到客户端
        dos.writeUTF("打招呼干嘛呢");
        
        accept.close();
        server.close();
        
        
    }
}

TestClientSocket.java

package com.sxt.net;
import java.io.DataInputStream;
import java.io.DataOutputStream;
/*
 * 客户端
 */
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;

public class TestClientSocket {
    public static void main(String[] args) throws UnknownHostException, IOException {
        //指定发送服务端的主机IP  端口号
        Socket socket = new Socket(InetAddress.getLocalHost(), 8888);
        //通过输出流向服务端发送数据
        OutputStream outputStream = socket.getOutputStream();
        DataOutputStream dos = new DataOutputStream(outputStream);
        //将数据写出到服务端
        dos.writeUTF("客户端:你好 老兄");
        
        //通过输入流读取服务端的回应信息
        InputStream inputStream = socket.getInputStream();
        DataInputStream dis = new DataInputStream(inputStream);
        //读取流到程序
        String readUTF = dis.readUTF();
        //显示到控制台
        System.out.println(readUTF);
        socket.close();
    }
}

 

ServerSocket 和 ClientSocket (网络编程)