悉野小楼

导航

java socket使用例子

SocketServer.java
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class SocketServer {
    public static void main(String[] args) {
        try {
            //建立一个服务器socket端口
            ServerSocket serverSocket = new ServerSocket(9999);
            Socket socket = serverSocket.accept();
            String strSend = "hello, you've connected to the server";
            OutputStream outputStream = socket.getOutputStream();
            InputStream inputStream = socket.getInputStream();
            byte[] bytes = strSend.getBytes();
            outputStream.write(bytes);
            outputStream.flush();
            if(inputStream.available() > 0) {
                int len = inputStream.available();
                byte[] bytesRead = new byte[len];
                inputStream.read(bytesRead);
                String str = new String(bytesRead);
                System.out.println(str);
            }
            inputStream.close();
            outputStream.close();
            socket.close();
        } catch (Exception ex) {

        }
    }
}
SocketClient.java
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;

public class SocketClient {

    public static void main(String[] args) {
        try {
            String strHost = "127.0.0.1";
            InetSocketAddress socketAddress = new InetSocketAddress(strHost, 9999);
            Socket socket = new Socket();
            socket.connect(socketAddress);
            String strSend = "hello, i'm client";
            OutputStream outputStream = socket.getOutputStream();
            InputStream inputStream = socket.getInputStream();
            byte[] bytes = strSend.getBytes();
            outputStream.write(bytes);
            outputStream.flush();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String line;
            while((line = bufferedReader.readLine()) != null) {
                System.out.println(line + "\r\n");
            }
            //要关闭各种
            bufferedReader.close();
            inputStreamReader.close();
            inputStream.close();
            outputStream.close();
            socket.close();
        }
        catch (Exception ex) {

        }
    }
}

例子下载

posted on 2020-06-02 13:25  悉野  阅读(447)  评论(0编辑  收藏  举报