快速学习JAVA例子

JAVA example11


import java.io.BufferedReader;
import java.io.InputStreamReader;

/**
 * Created by summing on 16/8/7.
 * 方法说明:构造器,运行系统命令
 * 输入参数:String cmdline 命令字符
 * 返回类型:
 * 利用Java中Process类提供的方法让Java虚拟机截获被调用程序运行标准输出
 */
public class CmdExe {

    public CmdExe(String cmdline){
        try{
            String line;
            Process p = Runtime.getRuntime().exec(cmdline); //运行系统命令
            BufferedReader input = new BufferedReader(
                new InputStreamReader(p.getInputStream()));//使用缓存输出流获取屏幕输出

            while((line = input.readLine()) != null){//读取屏幕输出
                System.out.println("java print:" + line);
            }

            input.close();//关闭缓存输出
        }catch (Exception e){
            e.printStackTrace();//也是打印出异常,但是它还将显示出更深的调用信息
        }
    }

    public static void main(String args[]){
        new CmdExe("ls");
    }
}

JAVA example12

实现一个简单的JAVA服务器的服务端和客户端程序。首先是写一个Server类,这个类用来监听8888端口,并从这个端口接收消息然后输出。然后是一个Client类,这个类连接上面启动的Server类,然后接收用户输入。

先运行Server后运行Client。

package example12;

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


/**
 * Created by summing on 16/8/7.
 * 服务器端
 */
public class SampleServer {
    public static void main(String[] args) throws Exception {
        //在8888端口建立一个服务器套接字 ServerSocket
        ServerSocket mySock = new ServerSocket(8888);
        //等待监听是否有客户端连接 waiting for client
        Socket sock = mySock.accept();
        //输入缓存
        BufferedReader in = new BufferedReader((
                new InputStreamReader(sock.getInputStream())));
        //输出缓存
        PrintWriter out = new PrintWriter(new BufferedWriter(
                new OutputStreamWriter(sock.getOutputStream())), true);

        System.out.println("Client say:" + in.readLine());
        out.println("I am Server, my port is 8888");
        sock.close();
    }
}
package example12;

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

/**
 * Created by summing on 16/8/7.
 * 用户端
 */
public class SimpleClient {

    public static void main(String[] args) throws Exception {
        //获取IP地址
        InetAddress addr = InetAddress.getLocalHost();
        String ipname = addr.getHostAddress();
        System.out.println(ipname);
        //打开8888端口,与服务器建立连接
        Socket sock = new Socket(ipname, 8888);

        //缓存输入 reader
        BufferedReader in = new BufferedReader((
                new InputStreamReader(sock.getInputStream())));
        //缓存输出 Writer
        PrintWriter out = new PrintWriter(new BufferedWriter(
                new OutputStreamWriter(sock.getOutputStream())), true);

        //向服务器发送信息 out to client
        out.println("hello my java client");
        //从服务器接收信息 in readline
        System.out.println(in.readLine());

        sock.close();
    }
}

Java example13

多线程的JAVA客户端与服务器的建立与通信

package example13;

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

/**
 * Created by summing on 16/9/7.
 * Title: 多线程服务器
 */

public class CompServer {
    public static void main(String[] args) throws Exception {
        //在8888端口建立一个服务器套接字 ServerSocket
        ServerSocket server = new ServerSocket(8888);
        System.out.println("Server starting...");

        while (true) {
            //等待监听是否有客户端连接 waiting for client
            Socket sk = server.accept();
            System.out.println("Accepting Connection...");

            //启动服务线程
            new ServerThread(sk).start();
        }
    }
}

//建立服务器线程,为多个客户端服务
class ServerThread extends Thread {
    private Socket sock;

    ServerThread(Socket sock) {
        this.sock = sock;
    }

    // 把需要并行处理的代码放在run()方法中
    // start()方法启动线程将自动调用 run()方法,这是由jvm的内存机制规定的
    public void run() {
        BufferedReader in = null;
        PrintWriter out = null;

        try {

            in = new BufferedReader(
                    new InputStreamReader(sock.getInputStream()));
            out = new PrintWriter(new BufferedWriter(
                    new OutputStreamWriter(sock.getOutputStream())), true);

            while (true) {
                //接收来自客户端的请求,根据不同的命令返回不同的信息
                String cmd = in.readLine();
                System.out.println("cmd:" + cmd);
                if (cmd == null) break;

                if (cmd.toUpperCase().startsWith("BYE")) {
                    out.println("Client say bye.");
                    break;
                } else {
                    out.println("Hello I am server!");
                }
            }
        } catch (IOException e) {
            System.out.println(e);
        } finally {
            System.out.println("Closing Connection in Server...");
            //最后释放资源
            try {
                if (in != null) in.close();
                if (out != null) out.close();
                if (sock != null) sock.close();
            } catch (IOException e) {
                System.out.println("close server err:" + e);
            }
        }
    }
}
package example13;

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

/**
 * Created by summing on 16/9/7.
 * Title: 多线程客户端
 */
public class CompClient {
    //屏蔽本来应该静态访问,但是使用了对象访问的警告
    //suppress warnings relative to incorrect static access
    @SuppressWarnings("static-access")
    public static void main(String[] args) throws IOException, InterruptedException {
        InetAddress addr = InetAddress.getLocalHost();
        String addrIP = addr.getHostAddress();

        for (int i = 0; i < 10; i++) {
            new SocketThreadClient(addrIP);
        }

        Thread.currentThread().sleep(1000);
    }
}

class SocketThreadClient extends Thread {
    public static int count = 0;

    // 构造器,实现服务
    // 构造器就是和类名相同但无返回类型的方法, 构造器在类初始化的时候被调用通常被用来做一些初始化的工作
    public SocketThreadClient(String addrIP) {
        count++;
        BufferedReader in = null;
        PrintWriter out = null;
        Socket sock = null;

        try {
            sock = new Socket(addrIP, 8888);

            in = new BufferedReader(
                    new InputStreamReader(sock.getInputStream()));
            out = new PrintWriter(new BufferedWriter(
                    new OutputStreamWriter(sock.getOutputStream())), true);

            // 向服务器发送请求
            System.out.println("count:" + count);
            out.println("I am Client, coming");
            System.out.println(in.readLine());
            out.println("Client say byebye");
            System.out.println(in.readLine());

        } catch (IOException e) {
            System.out.println(e);
        } finally {
            out.println("Client End");

            try {
                if (in != null) in.close();
                if (out != null) out.close();
                if (sock != null) sock.close();

            } catch (IOException e) {
                System.out.println("close client error:" + e);
            }

        }
    }
}

JAVA example14

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;

/**
 * Created by summing on 16/10/7.
 * Title: 获取一个URL文本
 * Description: 通过使用URL类,构造一个输入对象,并读取其内容。
 */
public class getURL {
    public static void main(String[] args) {
        String URL = "http://www.baidu.com";
        //运行该实体类
        new getURL(URL);
    }

    /*
    * 方法说明: 构造器
    * 输入参数: String URL 网址
    * 返回类型: none
    * */
    public getURL(String URL) {
        try {
            //创建一个URL对象
            URL url = new URL(URL);
            //读取从服务器返回的所有文本
            BufferedReader in = new BufferedReader(
                    new InputStreamReader(url.openStream()));

            String str;
            while ((str = in.readLine()) != null) {
                display(str);
            }

            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /*
    * 方法说明: 显示提取URI信息
    * */
    private void display(String s) {
        if (s != null) {
            System.out.println(s);
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值