手记

Socket ,DataOutputStream,DataInputStream技术通信代码

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
    public static void main(String args[]) throws Exception {
        ServerSocket serverSocket = new ServerSocket(10086);
        Socket socket = serverSocket.accept();
        InputStream is = socket.getInputStream();
        DataInputStream dis = new DataInputStream(is);
        String info = dis.readUTF();
        System.out.println("我是服务器,客户端说:" + info);
        socket.shutdownInput();
        OutputStream os = socket.getOutputStream();
        DataOutputStream dos = new DataOutputStream(os);
        dos.writeUTF("欢迎您!");
        dos.flush();
        dis.close();
        dos.close();
        os.close();
        is.close();
        socket.close();
        serverSocket.close();
    }
}

import java.io.*;

import java.net.Socket;

public class Client {

    public static void main(String args[]) throws Exception {

        Socket socket = new Socket("localhost", 10086);

        OutputStream os = socket.getOutputStream();

        DataOutputStream dos = new DataOutputStream(os);

        dos.writeUTF("用户名:admin;密码:123");

        dos.flush();

        socket.shutdownOutput();

        InputStream is = socket.getInputStream();

        DataInputStream dis = new DataInputStream(is);

        String info = dis.readUTF();

        System.out.println("我是客户端,服务器说:" + info);

        dis.close();

        is.close();

        dos.close();

        os.close();

        socket.close();

    }

}


3人推荐
随时随地看视频
慕课网APP