Java-网络程序开发

java.net包中有两个类:

  1. ServerSocket:封装支持TCP协议的操作类,主要工作在服务器端,勇于接受客户端请求
  2. Socket:同样是封装了TCP协议的类,每一个Socket对象都表示一个客户端

ServerSocket类方法:

  1. public ServerSocket(int port) throws IOException,开启指定端口监听
  2. public Socket accept() throws IOException,服务器接受客户端请求
  3. public void close() throws IOException,关闭服务器端

Socket类方法:

  1. pubilc Socket(String host, int port) throws UnkownHostException, IOException,指定要连接的ip和端口
  2. public OutStream getOutputStream() throws IOException,取得指定客户端的输出对象,通过PrintStream装饰操作
  3. public InputStream getInputStream() throws IOException,从指定的客户端读取数据,通过Scanner输出。

Server模型:

package com.joeaaa.demo19Net;

/*
* 服务器端:监听9999
*/
import java.io.IOException;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;

public class ServerTest {
    public static void main(String[] args) throws IOException {
        ServerSocket server = new ServerSocket(9999); //9999端口监听
        System.out.println("Server Started");
        Socket client = server.accept(); // 接受客户端连接,进入阻塞状态
        PrintStream out = new PrintStream(client.getOutputStream());
        out.println("hello, serversocket test"); // 向客户端输出
        out.close(); // 关闭输出流
        client.close(); // 关闭客户端
        server.close();// 关闭服务器端
        System.out.println("server closed");
    }
}

客户端模型:

package com.joeaaa.demo19Net;

/*
* 客户端:连接本地9999端口
*/
import java.io.IOException;
import java.net.Socket;
import java.util.Scanner;

public class ClientTest {
    public static void main(String[] args) throws IOException {
        Socket client = new Socket("localhost",9999);
        Scanner scan = new Scanner(client.getInputStream());
        scan.useDelimiter("\n"); //设置换行符
        if (scan.hasNext()){
            System.out.println("Server msg:  "+scan.next());
        }
        scan.close();
        client.close();
    }
}

网络开发经典模型:ECHO程序

客户端输入信息,服务器端接收后再前面加入ECHO:后返回给客户端。

EchoClient

package com.joeaaa.demo19Net;
/*
 * client发送信息
 * 输入bye结束
 */
import java.io.PrintStream;
import java.net.Socket;
import java.util.Scanner;

public class EchoClient {
    public static void main(String[] args) throws Exception {// 直接抛出异常
        Socket client = new Socket("localhost", 9999);// 连接服务器端
        Scanner input = new Scanner(System.in);
        Scanner scan = new Scanner(client.getInputStream());
        PrintStream out = new PrintStream(client.getOutputStream());
        input.useDelimiter("\n");
        scan.useDelimiter("\n");

        boolean flag = true;
        while (flag) {
            System.out.println("请输入要发送的指令:");
            if (input.hasNext()) {
                String str = input.next().trim();
                out.println(str);// 发送服务器数据
                if ("bye".equalsIgnoreCase(str)) {
                    flag = false;// 循环结束
                }
                if (scan.hasNext()) {
                    System.out.println(scan.next());// 输出回应数据
                }
            }
        }

        input.close();
        scan.close();
        out.close();
        client.close();
    }
}

EchoServer

package com.joeaaa.demo19Net;
/*
 * 接收client传入的信息,添加ECHO:后返回,
 */
import java.io.IOException;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

class EchoThread implements Runnable {
    private Socket client;

    public EchoThread(Socket client) {
        this.client = client;
    }

    @Override
    public void run() {
        try {
            Scanner scan = new Scanner(client.getInputStream());
            PrintStream out = new PrintStream(client.getOutputStream());
            boolean flag = true;// 控制多次连接操作
            while (flag) {
                if (scan.hasNext()) {
                    String str = scan.next().trim();// 得到客户端发送的信息
                    if ("end".equalsIgnoreCase(str)) {// 程序结束条件
                        out.println("Server's shut down,See you later!");
                        flag = false;// 退出循环
                    } else {// 应该回应输入信息
                        out.println("ECHO:" + str);
                    }
                }
            }
            scan.close();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

public class EchoServer {
    public static void main(String[] args) throws Exception {// 此处直接抛错
        ServerSocket server = new ServerSocket(9999);
        System.out.println("等待客户端连接....");
        boolean flag = true;
        while (flag) {
            Socket cilent = server.accept();// 等待客户端连接
            new Thread(new EchoThread(cilent)).start();
        }
        server.close();

    }
}