网络编程(2)

TCP-大写转换-客户端

public class TransClient {

    /**
     * @param args
     * @throws IOException 
     * @throws  
     */
    public static void main(String[] args) throws IOException {
        System.out.println("客户端运行......");
        // 客户端:
        // 步骤:
        // 1,创建socket,明确地址和端口。
        Socket s = new Socket("192.168.1.223", 10005);

        // 2,源:键盘录入。获取需要转换的数据。
        BufferedReader bufr = new BufferedReader(new InputStreamReader(System.in));

        // 3,目的:网络,socket输出流。将录入的数据发送到服务端。
//      OutputStream out = s.getOutputStream();
        //既然都是字符数据,为了便于操作,使用额外功能,转换。同时提高效率。
        //BufferedWriter bufOut = new BufferedWriter(new OutputStreamWriter(out));可以使用打印流
        PrintWriter out = new PrintWriter(s.getOutputStream(),true);

        // 4,源:socket,socket读取流,读取服务端发回来的大写数据。
//      InputStream in = s.getInputStream();
        BufferedReader bufIn = new BufferedReader(new InputStreamReader(s.getInputStream()));

        // 5,目的:客户端显示器,将大写数据显示出来。直接使用输出语句。

        // 6,频繁的读写操作。
        String line = null;
        while((line=bufr.readLine())!=null){

            //将读取键盘的数据发送到服务端。
            out.println(line);
//          out.flush();
            if("over".equals(line)){
                break;
            }

            //读取服务端返回的数据。
            String upperText = bufIn.readLine();
            System.out.println(upperText);
        }

        // 7,关闭资源。
        s.close();
    }

}

TCP-大写转换-服务端

public class TransServer {

    /**
     * @param args
     * @throws IOException
     */
    public static void main(String[] args) throws IOException {

        System.out.println("服务端运行....");
        // 服务端:
        // 思路:
        // 1,创建服务端socket 明确端口。
        ServerSocket ss = new ServerSocket(10005);
        while (true) {
            // 获取客户端对象。
            Socket s = ss.accept();
            System.out.println(s.getInetAddress().getHostAddress()+".....connected");

            // 2,源:socket输入流。读取客户端的发过来的数据。
            BufferedReader bufIn = new BufferedReader(new InputStreamReader(
                    s.getInputStream()));

            // 3,目的:socket输出流。将转成大写的数据发送给客户端。
            PrintWriter out = new PrintWriter(s.getOutputStream(),true);

            // 4,频繁的读写操作。
            String line = null;
            while ((line = bufIn.readLine()) != null) {
                if("over".equals(line)){//如果客户端发过来的是over,转换结束。
                    break;
                }
                System.out.println(line);
                // 将读取到的字母数据转成大写,发回给客户端。
                out.println(line.toUpperCase());
//              out.flush();
            }
            // 5,关闭客户端。
            s.close();
        }

    }

}

TCP-上传文本文件

客户端

public class UploadTextClient {

    /**
     * @param args
     * @throws IOException 
     * @throws UnknownHostException 
     */
    public static void main(String[] args) throws UnknownHostException, IOException {
        System.out.println("上传文件客户端运行......");
        // 客户端:
        // 步骤:
        // 1,创建socket,明确地址和端口。
        Socket s = new Socket("192.168.1.223", 10006);

        // 2,源:读取文本文件。获取需要转换的数据。
        BufferedReader bufr = new BufferedReader(new FileReader("tempfile\\client.txt"));

        // 3,目的:网络,socket输出流。将录入的数据发送到服务端。
        PrintWriter out = new PrintWriter(s.getOutputStream(),true);

        // 4,频繁的读写操作。
        String line = null;
        while((line=bufr.readLine())!=null){

            out.println(line);

        }

        //给服务端发送一个结束标记。这个标记是约定标记。有点麻烦。可以更简单。使用socket对象的shutdownOutput();
//      out.println("over");
        s.shutdownOutput();//向服务端发送了结束标记。可以让服务端结束读取的动作。


        // 5,源:socket,socket读取流,读取服务端发回来的上传成功信息。
        BufferedReader bufIn = new BufferedReader(new InputStreamReader(s.getInputStream()));
        String info = bufIn.readLine();
        System.out.println(info);

        // 6,关闭资源。
        bufr.close();
        s.close();


    }

}

服务端

public class UploadTextServer {

    /**
     * @param args
     * @throws IOException 
     */
    public static void main(String[] args) throws IOException {


        System.out.println("上传文本服务端运行....");
        // 服务端:
        // 思路:
        // 1,创建服务端socket 明确端口。
        ServerSocket ss = new ServerSocket(10006);
        while (true) {
            // 获取客户端对象。
            Socket s = ss.accept();
            System.out.println(s.getInetAddress().getHostAddress()+".....connected");

            // 2,源:socket输入流。读取客户端的发过来的数据。
            BufferedReader bufIn = new BufferedReader(new InputStreamReader(
                    s.getInputStream()));

            // 3,目的:文件。
            PrintWriter pw = new PrintWriter(new FileWriter("tempfile\\server.txt"),true);

            // 4,频繁的读写操作。
            String line = null;
            while ((line = bufIn.readLine()) != null) {
//              if("over".equals(line)){
//                  break;
//              }
                pw.println(line);
            }

            // 5,发回给客户端上传成功字样。
            PrintWriter out = new PrintWriter(s.getOutputStream(),true);
            out.println("上传成功");

            // 6,关闭客户端。
            s.close();
        }


    }

}

上传图片-客户端

public class UploadPicClient {

    /**
     * @param args
     * @throws IOException 
     * @throws  
     */
    public static void main(String[] args) throws IOException {
        System.out.println("上传图片客户端运行......");
        //1,创建socket。
        Socket s = new Socket("192.168.1.223", 10007);

        //2,读取源图片。
        File picFile = new File("tempfile\\1.jpg");
        FileInputStream fis = new FileInputStream(picFile);

        //3,目的是socket 输出流。
        OutputStream out = s.getOutputStream();

        byte[] buf = new byte[1024];

        int len = 0;
        while((len=fis.read(buf))!=-1){
            out.write(buf,0,len);
        }

        //告诉服务器端图片数据发送完毕,不要等着读了。
        s.shutdownOutput();

        //读取上传成功字样。
        InputStream in = s.getInputStream();
        byte[] bufIn = new byte[1024];
        int lenIn = in.read(bufIn);
        System.out.println(new String(bufIn,0,lenIn));


        //关闭。
        fis.close();
        s.close();

    }

}

上传图片

public class UploadPic implements Runnable {

    private Socket s;

    public UploadPic(Socket s) {
        this.s = s;
    }

    @Override
    public void run() {

        try {
            String ip = s.getInetAddress().getHostAddress();
            System.out.println(ip + ".....connected");

            // 读取图片数据。
            InputStream in = s.getInputStream();

            // 写图片数据到文件。
            File dir = new File("e:\\uploadpic");
            if (!dir.exists()) {
                dir.mkdir();
            }
            // 为了避免覆盖,通过给重名的文件进行编号。
            int count = 1;
            File picFile = new File(dir, ip + "(" + count + ").jpg");
            while (picFile.exists()) {
                count++;
                picFile = new File(dir, ip + "(" + count + ").jpg");
            }
            FileOutputStream fos = new FileOutputStream(picFile);

            byte[] buf = new byte[1024];
            int len = 0;
            while ((len = in.read(buf)) != -1) {
                fos.write(buf, 0, len);
            }

            // 给客户端一个回馈信息。
            OutputStream out = s.getOutputStream();
            out.write("上传成功".getBytes());

            // 关闭资源。
            fos.close();
            s.close();
        } catch (IOException e) {

        }

    }

}

上传图片-服务端

public class UploadPicServer {

    /**
     * @param args
     * @throws IOException
     */
    public static void main(String[] args) throws IOException {
        System.out.println("上传图片服务端运行......");
        // 创建server  socket 。
        ServerSocket ss = new ServerSocket(10007);

        while (true) {
            // 获取客户端。
            Socket s = ss.accept();

            //实现多个客户端并发上传,服务器端必须启动做个线程来完成。
            new Thread(new UploadPic(s)).start();

        }
    }

}

UploadPicByGUI

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;

import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
import javax.swing.filechooser.FileNameExtensionFilter;

/**
 * This code was edited or generated using CloudGarden's Jigloo SWT/Swing GUI
 * Builder, which is free for non-commercial use. If Jigloo is being used
 * commercially (ie, by a corporation, company or business for any purpose
 * whatever) then you should purchase a license for each developer using Jigloo.
 * Please visit www.cloudgarden.com for details. Use of Jigloo implies
 * acceptance of these licensing terms. A COMMERCIAL LICENSE HAS NOT BEEN
 * PURCHASED FOR THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED LEGALLY FOR
 * ANY CORPORATE OR COMMERCIAL PURPOSE.
 */
public class UploadPicByGUI extends javax.swing.JFrame {
    private JTextField jTextField1;
    private JButton jButton1;
    private JButton jButton2;
    private JTextArea jTextArea1;
    private File srcFile;

    /**
     * Auto-generated main method to display this JFrame
     */
    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                UploadPicByGUI inst = new UploadPicByGUI();
                inst.setLocationRelativeTo(null);
                inst.setVisible(true);
            }
        });
    }

    public UploadPicByGUI() {
        super();
        initGUI();
    }

    private void initGUI() {
        try {
            getContentPane().setLayout(null);
            setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
            {
                jTextField1 = new JTextField();
                getContentPane().add(jTextField1);
                jTextField1.setBounds(19, 27, 424, 47);
            }
            {
                jButton1 = new JButton();
                getContentPane().add(jButton1);
                jButton1.setText("\u6d4f\u89c8...");
                jButton1.setBounds(460, 27, 91, 47);
                jButton1.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent evt) {
                        jButton1ActionPerformed(evt);
                    }
                });
            }
            {
                jTextArea1 = new JTextArea();
                getContentPane().add(jTextArea1);
                jTextArea1.setBounds(19, 95, 424, 130);
            }
            {
                jButton2 = new JButton();
                getContentPane().add(jButton2);
                jButton2.setText("\u4e0a\u4f20");
                jButton2.setBounds(460, 100, 91, 125);
                jButton2.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent evt) {
                        jButton2ActionPerformed(evt);
                    }
                });
            }
            pack();
            this.setSize(570, 296);
        } catch (Exception e) {
            // add your error handling code here
            e.printStackTrace();
        }
    }

    private void jButton1ActionPerformed(ActionEvent evt) {

        JFileChooser chooser = new JFileChooser();
        FileNameExtensionFilter filter = new FileNameExtensionFilter(
                "JPG & Images", "jpg");
        chooser.setFileFilter(filter);
        int returnVal = chooser.showOpenDialog(this);
        if (returnVal == JFileChooser.APPROVE_OPTION) {

            srcFile = chooser.getSelectedFile();

            jTextField1.setText(srcFile.getAbsolutePath());

        }

    }

    private void uploadPic(File srcFile) throws IOException {
        Socket s = new Socket("192.168.1.223", 10007);

        // 2,读取源图片。
        FileInputStream fis = new FileInputStream(srcFile);

        // 3,目的是socket 输出流。
        OutputStream out = s.getOutputStream();

        byte[] buf = new byte[1024];

        int len = 0;
        while ((len = fis.read(buf)) != -1) {
            out.write(buf, 0, len);
        }

        // 告诉服务器端图片数据发送完毕,不要等着读了。
        s.shutdownOutput();

        // 读取上传成功字样。
        InputStream in = s.getInputStream();
        byte[] bufIn = new byte[1024];
        int lenIn = in.read(bufIn);
        jTextArea1.setText(new String(bufIn, 0, lenIn));

        // 关闭。
        fis.close();
        s.close();

    }

    private void jButton2ActionPerformed(ActionEvent evt) {
        if(srcFile==null){
            jTextArea1.setText("请选择一个扩展名为jpg的图片");
            return;
        }

        if(srcFile.length()>1024*1024*3){
            jTextArea1.setText("文件体积过大,不行!");
            return;
        }


        try {
            uploadPic(srcFile);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

}

MyBrowser

public class MyBrowser {

    /**
     * @param args
     * @throws IOException 
     * @throws UnknownHostException 
     */
    public static void main(String[] args) throws UnknownHostException, IOException {

        /*
         * 模拟一个浏览器。发送之前IE发送的http消息。
         */
        Socket s = new Socket("192.168.1.223",8080);
        //把IE的信息发送给服务端。
        PrintWriter out = new PrintWriter(s.getOutputStream(),true);
        out.println("GET /myweb/3.html HTTP/1.1");
        out.println("Accept: */*");
        out.println("Host: 192.168.1.223:8080");
        out.println("Connection: close");
        out.println();//空行。

        //读取服务端的数据。
        InputStream in = s.getInputStream();
        byte[] buf = new byte[1024];
        int len = in.read(buf);
        String text = new String(buf,0,len);
        System.out.println(text);

        s.close();


    }

}

MyServer

public class MyServer {

    /**
     * @param args
     * @throws IOException 
     */
    public static void main(String[] args) throws IOException {


        /*
         *  自定义server 服务端
         *  获取浏览器的信息。并反馈信息。
         */
        System.out.println("my server run....");
        ServerSocket ss = new ServerSocket(9090);

        Socket s = ss.accept();
        System.out.println(s.getInetAddress().getHostAddress()+"....connected");

        //读取客户端的数据。
        InputStream in = s.getInputStream();
        byte[] buf = new byte[1024];
        int len = in.read(buf);
        String text = new String(buf,0,len);
        System.out.println(text);

        //给客户端回馈数据。
        PrintWriter out = new PrintWriter(s.getOutputStream(),true);
        out.println("<font color='red' size='7'>欢迎光临</font>");


        s.close();
        ss.close();


    }

}

MyBrowserByGUI

public class MyBrowserByGUI extends javax.swing.JFrame {
    private JTextField jTextField1;
    private JButton jButton1;
    private JTextArea jTextArea1;
    private JScrollPane jScrollPane1;

    /**
    * Auto-generated main method to display this JFrame
    */
    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                MyBrowserByGUI inst = new MyBrowserByGUI();
                inst.setLocationRelativeTo(null);
                inst.setVisible(true);
            }
        });
    }

    public MyBrowserByGUI() {
        super();
        initGUI();
    }

    private void initGUI() {
        try {
            setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
            getContentPane().setLayout(null);
            {
                jTextField1 = new JTextField();
                getContentPane().add(jTextField1);
                jTextField1.setBounds(12, 18, 522, 44);
            }
            {
                jButton1 = new JButton();
                getContentPane().add(jButton1);
                jButton1.setText("\u8f6c\u5230");
                jButton1.setBounds(546, 18, 84, 44);
                jButton1.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent evt) {
                        jButton1ActionPerformed(evt);
                    }
                });
            }
            {
                jScrollPane1 = new JScrollPane();
                getContentPane().add(jScrollPane1);
                jScrollPane1.setBounds(12, 68, 617, 358);
                {
                    jTextArea1 = new JTextArea();
                    jScrollPane1.setViewportView(jTextArea1);
                }
            }
            pack();
            this.setSize(649, 479);
        } catch (Exception e) {
            //add your error handling code here
            e.printStackTrace();
        }
    }

    private void jButton1ActionPerformed(ActionEvent evt) {

        try {
            accessServer();
        } catch (UnknownHostException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }


    }

    /**
     * @throws UnknownHostException
     * @throws IOException
     */
    private void accessServer() throws UnknownHostException, IOException {

        String str_url = jTextField1.getText();
        URL url = new URL(str_url);

        URLConnection conn = url.openConnection();

        InputStream in = conn.getInputStream();
        byte[] buf = new byte[1024];
        int len = in.read(buf);
        String text = new String(buf,0,len);
        jTextArea1.setText(text);

    }

}

url

public class URLDemo {

    /**
     * @param args
     * @throws IOException 
     */
    public static void main(String[] args) throws IOException {

        String str_url = "http://192.168.1.223:8080/myweb/2.html";

        //将url地址封装成对象。
        URL url = new URL(str_url);

//      System.out.println("getProtocol:"+url.getProtocol());
//      System.out.println("getHost:"+url.getHost());
//      System.out.println("getPort:"+url.getPort());
//      System.out.println("getPath:"+url.getPath());
//      System.out.println("getFile:"+url.getFile());
//      System.out.println("getQuery:"+url.getQuery());

        //获取指定资源的连接对象。//封装了socket。
        URLConnection conn = url.openConnection();

//      System.out.println(conn);

        InputStream in = conn.getInputStream();
        byte[] buf = new byte[1024];
        int len = in.read(buf);
        String text = new String(buf,0,len);
        System.out.println(text);

    }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值