简易socket通信

1 服务端

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

public class SocketServerDemo implements Runnable{
    public int port;

    public SocketServerDemo(int port) {
        this.port = port;
    }

    @Override
    public void run() {
        try {
            ServerSocket server = new ServerSocket(port);
            while (true) {
                //等待client的请求
                System.out.println("waiting...");
                Socket socket = server.accept();
                // 接收客户端的数据
                DataInputStream in = new DataInputStream(socket.getInputStream());
                String string = in.readUTF();
                System.out.println("client:" + string);
                // 发送给客户端数据
                DataOutputStream out = new DataOutputStream(socket.getOutputStream());
                out.writeUTF("hi,i am hserver!i say:" + string);
                socket.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        SocketServerDemo serverApp = new SocketServerDemo(8080);
        serverApp.run();
    }
}

2 客户端

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.Socket;
import java.util.Scanner;

public class SocketClientDemo{
    public static void main(String[] args) {
        while (true) {
            try {
                Socket socket = new Socket("192.168.1.3", 8080);
                System.out.println("please input...");
                Scanner scanner = new Scanner(System.in);
                String p = scanner.nextLine();
                // 发送给服务器的数据
                DataOutputStream out = new DataOutputStream(socket.getOutputStream());
                out.writeUTF(p);
                // 接收服务器的返回数据
                DataInputStream in = new DataInputStream(socket.getInputStream());
                System.out.println("hserver:" + in.readUTF());
                if (p.equals("bye")) {
                    socket.close();
                    break;
                }
                socket.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

}

备注:先运行服务端,再运行客户端

你可能感兴趣的:(java)