编程语言
首页 > 编程语言> > Java网络编程 - 服务器端和客户端的连接和信息传递实现

Java网络编程 - 服务器端和客户端的连接和信息传递实现

作者:互联网

1、Client(客户端代码)

package cn.qi.Client;

import java.io.*;
import java.net.Socket;

public class Client {
    Socket clientSocket;
    Client() {}

    public void write() throws IOException {
        // 建立连接到服务器端的socket
        clientSocket = new Socket("127.0.0.1",5000);

        // 客户端向服务器端发送消息,通过socket建立管道
        OutputStream os = clientSocket.getOutputStream();
        // 通过socket获取IO管道,纯IO操作
        PrintWriter pw = new PrintWriter(os);

        pw.write("hello");
        pw.flush();
        // 流的关闭
        pw.close();

        // 关闭socket连接
        clientSocket.close();
    }

    public void read() throws IOException {
        // 建立连接到服务器端的socket
        clientSocket = new Socket("127.0.0.1",5000);


        // socket实现纯IO
        InputStream is = clientSocket.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        String st = br.readLine();
        br.close();
        System.out.println(st);

        // 关闭socket连接
        clientSocket.close();
    }
}

 

2、Server(服务器端代码)

package cn.qi.Server;

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

public class Server {
    ServerSocket serverSocket;
    Server() {}

    public void sent() throws IOException {
        // 建立severSocket,监听对应端口
        serverSocket = new ServerSocket(5000);


        while(true) {
            // server监听端口,监听成功,生成socket
            Socket socket= serverSocket.accept();

            // 客户端向服务器端发送消息,通过socket建立管道
            OutputStream os = socket.getOutputStream();
            // 通过socket获取IO管道,纯IO操作
            PrintWriter pw = new PrintWriter(os);

            pw.write("hello");
            pw.flush();
            // 流的关闭
            pw.close();

            // 本次请求的socket的关闭
            socket.close();
        }

    }

    public void getInfo() throws IOException {
        // 建立severSocket,监听对应端口
        serverSocket = new ServerSocket(5000);


        while(true) {
            // server监听端口,监听成功,生成socket
            Socket socket= serverSocket.accept();

            // socket实现纯IO
            InputStream is = socket.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            String st = br.readLine();
            br.close();

            System.out.println(st);

            // 本次请求的socket的关闭
            socket.close();
        }

    }
}

 

标签:Java,socket,pw,clientSocket,new,close,客户端,Socket,服务器端
来源: https://www.cnblogs.com/GjqDream/p/11623582.html