java之网络编程1-Tcp

一,了解之前先了解一下网络基础

首先理清一个概念:网络编程 != 网站编程,网络编程现在一般称为TCP/IP编程

一般的网络编程都称为Socket编程,Socket的英文意思是“插座”

网络编程的目的:直接或者间接的通过网络协议与其他计算机进行通信。

网络编程中有两个主要的问题:

-->如何准确定为网络上一台或者多台主机:IP和端口号

-->找到主机后如何可靠搞笑的进行数据传输:Tcp/Ip 协议(四层)

二,网络通信要素

网络通信要素1:IP地址,通过Ip,可以唯一的定为互联网上的一台主机

    ip地址唯一定为一台主机,而端口号定为主机上的某一个正在运行的软件

通讯要素2:网络通信协议TCP/IP协议

三,TCP编程案例1:客户端给服务端发消息,服务端输出此消息到控制台

import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author: wsj
 * @date: 2018/10/14
 * @time: 15:08
 */
//客户端给服务端发消息,服务端输出此消息到控制台
public class testCS {

    //客户端
    @Test
    public void client(){
        Socket socket = null;
        OutputStream outputStream = null;
        try {
            //1.创建一个Scoket 的对象,通过构造器知名服务端的IP地址,以及其接收的端口号
            socket = new Socket(InetAddress.getByName("127.0.0.1"),9090);
            //2.getOutputStream():发送数据,方法返回OutputStream对象
            outputStream = socket.getOutputStream();
            //3.具体的输出过程
            outputStream.write(("我是客户端,我的地址是"+socket.getInetAddress().getHostAddress()).getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            //4.关闭流和Socket
            if(null != outputStream) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(null  != socket) {
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }
//服务端
    @Test
    public void server(){
        ServerSocket ss = null;
        Socket st = null;
        InputStream is = null;
        try {
            //1.创建一个ServerSocket的对象,通过构造器指明自身的端口号
            ss = new ServerSocket(9090);
            //2.调用其accept()方法,返回一个Socket对象
            st = ss.accept();
            //3.调用Socket对象的getInputStream() 获取一个从客户端发送过来的输入流
            is = st.getInputStream();
            //4.对获取的输入流进行操作
            byte[] b = new byte[50];
            int len;
            while((len = is.read(b)) != -1){
                String str = new String(b,0,len);
                System.out.println(str+"\n");
                System.out.println("收到来自"+st.getInetAddress().getHostAddress()+"的请求并已回应");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            //5.关闭流和Socket 和ServerSocket对象
            if (null != is) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != ss) {
                try {
                    ss.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != st) {
                try {
                    st.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }

    }
}

TCP编程案例2:客户端给服务端发消息,服务端输出此消息到控制台,同时发送已收到信息给客户端

import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author: wsj
 * @date: 2018/10/14
 * @time: 15:08
 */
//客户端给服务端发消息,服务端输出此消息到控制台
public class testCS {

    //客户端
    @Test
    public void client(){
        Socket socket = null;
        OutputStream outputStream = null;
        InputStream is = null;
        try {
            //1.创建一个Scoket 的对象,通过构造器知名服务端的IP地址,以及其接收的端口号
            socket = new Socket(InetAddress.getByName("127.0.0.1"),9090);
            //2.getOutputStream():发送数据,方法返回OutputStream对象
            outputStream = socket.getOutputStream();
            //3.具体的输出过程
            outputStream.write(("我是客户端,我的地址是"+socket.getInetAddress().getHostAddress()).getBytes());
            //声明给服务端发送的东西完毕
            socket.shutdownOutput();
            //接收服务端的回应
             is = socket.getInputStream();
            byte[] b = new byte[50];
            int len;
            while((len = is.read(b)) != -1){
                String str = new String(b,0,len);
                System.out.println(str);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            //4.关闭流和Socket
            if(null != outputStream) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(null  != socket) {
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }
//服务端
    @Test
    public void server(){
        ServerSocket ss = null;
        Socket st = null;
        InputStream is = null;
        OutputStream outputStream = null;
        try {
            //1.创建一个ServerSocket的对象,通过构造器指明自身的端口号
            ss = new ServerSocket(9090);
            //2.调用其accept()方法,返回一个Socket对象
            st = ss.accept();
            //3.调用Socket对象的getInputStream() 获取一个从客户端发送过来的输入流
            is = st.getInputStream();
            //4.对获取的输入流进行操作
            byte[] b = new byte[50];
            int len;
            while((len = is.read(b)) != -1){
                String str = new String(b,0,len);
                System.out.println(str);
            }
//            if(st.isInputShutdown()) {
                //给予客户端回应
                outputStream = st.getOutputStream();
                outputStream.write("我已经收到,这是给你(客户端)的回应哦".getBytes());
//            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            //5.关闭流和Socket 和ServerSocket对象
            if (null != is) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != ss) {
                try {
                    ss.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != st) {
                try {
                    st.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }

    }
}

一般关流的时候,遵循从后往前的顺序。

案例3:从客户端发送文件给服务端,服务端保存到本地,并返回"发送成功"给客户端,并关闭相关连接

import org.junit.Test;

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

/**
 * @author: wsj
 * @date: 2018/10/14
 * @time: 16:21
 */
//从客户端发送文件给服务端,服务端保存到本地,并返回"发送成功"给客户端,并关闭相关连接
//注意:本案例中的关流等操作都应该使用try...catch...finally 而不能使用throws Exception 本案例只是为书写方便~
public class socketTomcat { //客户端 @Test public void client() throws Exception{ // Socket socket = new Socket(InetAddress.getByName("127.0.0.1"),9898); // OutputStream outputStream = socket.getOutputStream(); FileInputStream file = new FileInputStream(new File("1.jpg")); byte[] b = new byte[1024]; int len ; while((len = file.read(b)) != -1){ outputStream.write(b,0,len); } // socket.shutdownOutput(); // InputStream inputStream = socket.getInputStream(); byte[] b1 = new byte[1024]; int len1 ; while((len1 = inputStream.read(b1)) != -1){ String str = new String(b1,0,len1); System.out.println(str); } inputStream.close(); outputStream.close(); file.close(); } @Test public void server() throws Exception{ ServerSocket serverSocket = new ServerSocket(9898); Socket socket = serverSocket.accept(); InputStream inputStream = socket.getInputStream(); FileOutputStream file = new FileOutputStream("3.jpg"); byte[] b1 = new byte[1024]; int len1 ; while((len1 = inputStream.read(b1)) != -1){ file.write(b1,0,len1); } OutputStream outputStream = socket.getOutputStream(); outputStream.write(("来自"+socket.getInetAddress().getHostAddress()+"的图片接收成功").getBytes()); outputStream.close(); file.close(); inputStream.close(); socket.close(); serverSocket.close(); } }

 

posted @ 2018-10-14 17:28  wsjun  阅读(173)  评论(0编辑  收藏  举报