Java 基于TCP的Socket网络编程的入门及示例

前言:各位周末愉快,因匿名台风来袭,窗外又是一波风雨交加,所以又是哪都不想去……话说给我天晴还不是一样窝在家里。。。好了,这篇是总结了tcp的socket,各种例子,应该是比较全了,记在这里,用到时可以过来瞄一眼。
原文出处:http://blog.csdn.net/u014158743/article/details/52895401

Socket网络这块很重要的是指定ip地址,端口号等基本信息。这些信息被封装在InetAddress中,所以先上一个小Demo介绍InetAddress的几个基本方法。

InetAddress入门Demo

    public static void main(String[] args) throws UnknownHostException {
        // TODO Auto-generated method stub

        // 获取本地主机的IP地址对象
        //InetAddress inet = InetAddress.getLocalHost();

        //获取任意一台主机的ip地址对象
        InetAddress  inet = InetAddress.getByName("www.baidu.com");

        // 获取ip地址
        String address = inet.getHostAddress();

        // 获取主机名
        String name = inet.getHostName();

        System.out.println(name + ":" + address);

    }

使用 Tcp 协议实现客户端给服务器端发送数据

TcpClient

    /**
     * 使用 Tcp 协议实现客户端给服务器端发送数据
     * 1:创建Socket端点,同时指明连接的服务器和端口
     * 2:使用Socket的发送功能发送数据
     * @throws IOException 
     * @throws UnknownHostException 
     */
    public static void main(String[] args) throws UnknownHostException, IOException {
        System.out.println("客户端启动......");
        //创建Socket客户端端点,同时指明连接的服务器和端口
        //这条语句执行成功,说明客户端对象创建成功,同时说明和服务器端连接成功
        //如果连接成功,说明和服务器端建立了一条通道
        //这条通道就是 Socket流(就是Socket客户端对象),这个Socket流中既有字节输入流,也有字节输出流
        Socket s = new Socket(InetAddress.getByName("192.168.1.212"),55555);


        //向服务器端发送数据
        //发送数据就是输出---从 Socket流中获取输出流
        OutputStream out = s.getOutputStream();

        //发送数据
        out.write("哥们,你好".getBytes());

        //接收数据
        InputStream in = s.getInputStream();
        byte[] arr = new byte[1024];
        int len =in.read(arr);
        System.out.println(new String(arr,0,len));

        s.close();
    }

TcpServer

    /**
     * 使用 Tcp实现服务器端
     * 1:创建 Socket端点,同时监听端口
     * 2:
     * @throws IOException 
     */
    public static void main(String[] args) throws IOException {
        System.out.println("服务器端启动......");
        //1:创建 Socket端点,同时监听端口
        ServerSocket  ss = new ServerSocket(55555);

        //得到客户端对象,也就是得到客户端使用的 Socket流,从而和客户端使用同一个流
        Socket s = ss.accept();
        System.out.println(s.getInetAddress().getHostAddress()+"连接到服务器端......");

        //接收客户端发送的数据
        //接收就是读取
        InputStream in = s.getInputStream();

        byte[] arr = new byte[1024];
        int len = in.read(arr);
        System.out.println(new String(arr,0,len));

        //向客户端发送数据
        OutputStream out = s.getOutputStream();
        out.write("你好,哥们".getBytes());

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

一个大写转换服务器Demo

客户端接收键盘输入的小写字符串,发送给服务器端,服务器端接收到小写字符串,转成大写,再发送给客户端

TextChangeClient

     /** 
     * 客户端:
     *  1:接收键盘输入的小写字符串
     *  2:发送小写字符串
     *  3:接收大写字符串
     * @throws IOException 
     * @throws UnknownHostException 
     */
    public static void main(String[] args) throws UnknownHostException, IOException {
        System.out.println("客户端启动....");
         //创建客户端对象
        Socket s = new Socket(InetAddress.getByName("192.168.1.212"),23333);

        //创建读取键盘输入的小写字符串的字符读取流
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        //创建发送小写字符串的字符输出流
        OutputStream out = s.getOutputStream();
        PrintWriter pw = new PrintWriter(out,true);

        //创建接收大写字符串的字符读取流 
        InputStream in = s.getInputStream();
        BufferedReader bin = new BufferedReader(new InputStreamReader(in));


        //循环读取键盘输入的数据,发送给服务器端,并接收返回的大写字符串
        String line = null;
        while((line = br.readLine())!=null) {
            if("over".equals(line))
                break;
            pw.println(line);//发送给服务器端
            System.out.println(bin.readLine());//接收返回的大写字符串
        }

        br.close();
        s.close();

    }

TextChangeServer

    /**               
     * 服务器端:
     * 接收小写字符串
     * 发送大写字符串
     * @throws IOException 
     */
    public static void main(String[] args) throws IOException {
        System.out.println("服务器端启动....");
        ServerSocket ss = new ServerSocket(23333);

        //得到客户端对象
        Socket s = ss.accept();
        System.out.println(s.getInetAddress().getHostAddress()+"连接到 服务器端.....");

        //创建接收小写字符串的字符读取流
        InputStream in = s.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(in));

        //创建发送大写字符串的字符输出流
        OutputStream out = s.getOutputStream();
        PrintWriter pw = new PrintWriter(out,true);

        String line = null;
        while((line = br.readLine())!=null)//循环读取客户端
        {
            pw.println(line.toUpperCase());
        }

        s.close();
    }

文本文件的上传的客户端Demo

客户端读取本地文件发送给服务器端,服务器端读取客户端,写入到服务器端的某个文件,服务器端返回”上传成功”

FileUploadClient

    /**
     * 客户端:
     * 1:读取本地文件
     * 2:发送给服务器端
     * 3:读取服务器端返回的"上传成功"
     * @throws IOException 
     * @throws UnknownHostException 
     */
    public static void main(String[] args) throws UnknownHostException, IOException {

        System.out.println("客户端启动.....");

        Socket s = new Socket(InetAddress.getByName("192.168.1.212"),24444);

        //创建读取本地文件的字符读取流
        BufferedReader br = new BufferedReader(new FileReader("temp\\tcptext.txt"));

        //创建 向服务器端发送数据的字符输出流
        OutputStream out = s.getOutputStream();
        PrintWriter pw = new PrintWriter(out,true);

        //创建读取服务器端返回的"上传成功"的字符读取流
        InputStream in = s.getInputStream();
        BufferedReader brr =  new BufferedReader(new InputStreamReader(in));

        //循环读取文件,发送到服务器端
        String line = null;
        while((line = br.readLine())!=null) {
            pw.println(line);
        }
        //向服务器端写入结束标记
        s.shutdownOutput();

        //读取服务器端返回的"上传成功"
        String result = brr.readLine();

        System.out.println(result);

        br.close();
        s.close();

    }

FileUploadServer

    /**          
     * 服务器端:
     * 接收客户端发送的数据
     * 写入到本地文件
     * 发送“上传成功”
     * @throws IOException 
     */
    public static void main(String[] args) throws IOException {
        System.out.println("服务器端启动....");
        ServerSocket ss = new ServerSocket(24444);

        Socket s = ss.accept();
        System.out.println(s.getInetAddress().getHostAddress()+"连接到服务器端.....");

        //创建接收客户端发送的数据字符读取流
        InputStream in = s.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(in));

        //创建写入到本地文件的字符输出流
        PrintWriter pw = new PrintWriter(new FileWriter("temp\\tcptext_copy.txt"),true);

        //创建发送“上传成功”的字符输出流
        OutputStream out = s.getOutputStream();
        PrintWriter pww = new PrintWriter(out,true);

        //循环读取客户端,写入到本地文件
        String line = null;
        while((line = br.readLine())!=null) {//读不到null
            pw.println(line);
        }

        pw.close();

        //发送上传成功
        pww.println("上传成功");

        s.close();
    }

图片上传的客户端Demo

PicUploadClient

    /**
     * 图片上传的客户端:
     * @throws IOException 
     * @throws UnknownHostException 
     * 
     */
    public static void main(String[] args) throws UnknownHostException, IOException {

          System.out.println("客户端启动.....");

          Socket s = new Socket(InetAddress.getByName("192.168.1.212"),25555);

          FileInputStream fis = new FileInputStream("temp\\tu.jpg");

          OutputStream out = s.getOutputStream();

          InputStream in = s.getInputStream();

          byte[] arr = new byte[1024];
          int len = 0;
          while((len = fis.read(arr))!=-1) {
              out.write(arr,0,len);
          }

          s.shutdownOutput();//写入结束标记

          //读取“上传成功”
          byte[] b = new byte[1024];
          int num = in.read(b);
          System.out.println(new String(b,0,num));

          fis.close();
          s.close(); 
    }

PicUploadServer

    /**
     *  图片上传的服务器端:
     * @throws IOException 
     */
    public static void main(String[] args) throws IOException {

        System.out.println("服务器端启动....");
        ServerSocket ss = new ServerSocket(25555);

        Socket s = ss.accept();
        System.out.println(s.getInetAddress().getHostAddress()+"连接到服务器端......");

        InputStream in = s.getInputStream();

        FileOutputStream fos = new FileOutputStream("temp\\tu_copy.jpg");

        OutputStream out = s.getOutputStream();

        //循环读取客户端数据,写入到本地文件
        byte[] arr = new byte[1024];
        int len = 0;
        while((len = in.read(arr))!=-1)
        {
            fos.write(arr,0,len);
        }
        fos.close();

        out.write("上传成功".getBytes());

        s.close();

    }

图片的并发上传Demo

PicUploadClient

同上

PicUploads

public class PicUploads implements Runnable {

    private Socket socket;
    public PicUploads(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {

          //所有上传的图片放到同一个目录下
          File dir = new File("f:\\tupian");
          if(!dir.exists())
              dir.mkdir();

          String ip = socket.getInetAddress().getHostAddress();
          System.out.println(ip+"连接到服务器端....");

          int num = 0;
          File file = new File(dir,ip+"("+(++num)+")"+".jpg");

          while(file.exists()) {
              file = new File(dir,ip+"("+(++num)+")"+".jpg");
          }

          try {

            InputStream in = socket.getInputStream();
            FileOutputStream fos = new FileOutputStream(file);

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

            OutputStream out = socket.getOutputStream();
            out.write("上传成功".getBytes());

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

}

PicUploadServer

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

        ServerSocket ss = new ServerSocket(25555);
        while(true) {
            Socket socket = ss.accept();
            new Thread(new PicUploads(socket)).start();
        }
    }

结束,祝成长。。。入门的同学可以实现图片的并发下载来做练习。
晚安。

猜你喜欢

转载自blog.csdn.net/u014158743/article/details/52895401