• JAVA SOCKET编程单线程简单实例


    服务端:

    package socketProgram;

    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.OutputStream;
    import java.io.PrintWriter;
    import java.net.ServerSocket;
    import java.net.Socket;
    import util.*;
    import util.screenShot;

    public class newServer {

    /**
    * @param args
    */
    public static void main(String[] args) throws IOException{
    // TODO Auto-generated method stub

    ServerSocket serverSocket = new ServerSocket(20000);
    Socket socket = new Socket();
    socket = serverSocket.accept();
    PrintWriter out = new PrintWriter(socket.getOutputStream());
    BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    while(true){
    String info = in.readLine();
    out.println("has receive...");
    out.flush();
    if(info.equals("截图")){
    //调用截图方法
    }else if(info.equals("进程")){
    //调用获取进程号方法
    }else if(info.equals("关机")){
    //调用关机方法
    }

    if(info.equals("end")){
    break;
    }
    }

    System.out.println("已跳出循环,接下来是关闭流");
    in.close();
    out.close();
    socket.close();
    serverSocket.close();


    }

    }

    ************************************************************************************************

    客户端:

    package socketProgram;

    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.PrintWriter;
    import java.net.Socket;

    public class newClient {

    /**
    * @param args
    */
    public static void main(String[] args) throws IOException{
    // TODO Auto-generated method stub
    Socket socket = new Socket("127.0.0.1",20000);
    BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    PrintWriter out = new PrintWriter(socket.getOutputStream());
    BufferedReader wt = new BufferedReader(new InputStreamReader(System.in));

    while(true){
    String info = wt.readLine();
    out.println(info);
    out.flush();

    if(info.equals("end")){
    break;
    }

    System.out.println(in.readLine());

    }
    wt.close();
    out.close();
    in.close();
    socket.close();

    }

    }

  • 相关阅读:
    CSS3 flex 布局 图片撑大 父级元素被放大 解决办法
    CentOS 下使用 cron crond crontab 执行定时任务
    Linux 安装 pcre
    Nginx 下载编译安装
    油猴脚本编写教程
    用图形来表达你的意思
    免费绘图软件drawio.io快捷键说明
    centos/Mac 下的多线程下载工具 axel
    巧用对象,生成不重复随机数
    mac 下 Redis5 BloomFilter 安装及与 python连用
  • 原文地址:https://www.cnblogs.com/chenbo820/p/6652149.html
Copyright © 2020-2023  润新知