Java网络编程之基于TCP协议

目录一、单向通信二、双向通信三、对象流传送四、加入完整的处理异常方式五、多线程接收用户请求

一、单向通信

功能:客户端发送一句话到服务器:

客户端:

public class TestClient {//客户端    //这是一个main方法,是程序的入口:    public static void main(String[] args) throws IOException {        //1.创建套接字:指定服务器的ip和端口号:        Socket s = new Socket("192.168.199.217",8888);        //2.对于程序员来说,向外发送数据 感受 --》利用输出流:        OutputStream os = s.getOutputStream();        DataOutputStream dos = new DataOutputStream(os);        //利用这个OutputStream就可以向外发送数据了,但是没有直接发送String的方法        //所以我们又在OutputStream外面套了一个处理流:DataOutputStream        dos.writeUTF("你好");        //3.关闭流  +  关闭网络资源:        dos.close();        os.close();        s.close();    }}

服务器端:

public class TestServer {//服务器    //这是一个main方法,是程序的入口:    public static void main(String[] args) throws IOException {        //1.创建套接字: 指定服务器的端口号        ServerSocket ss = new ServerSocket(8888);        //2.等着客户端发来的信息:        Socket s = ss.accept();//阻塞方法:等待接收客户端的数据,什么时候接收到数据,什么时候程序继续向下执行。        //accept()返回值为一个Socket,这个Socket其实就是客户端的Socket        //接到这个Socket以后,客户端和服务器才真正产生了连接,才真正可以通信了        //3.感受到的操作流:        InputStream is = s.getInputStream();        DataInputStream dis = new DataInputStream(is);        //4.读取客户端发来的数据:        String str = dis.readUTF();        System.out.println("客户端发来的数据为:"+str);                //5.关闭流+关闭网络资源:        dis.close();        is.close();        s.close();        ss.close();    }}

测试:

先开启客户端还是先开启服务器:先开服务器,再开启客户端 侧面验证:先开客户端:出错。

如图:

二、双向通信

客户端:

import java.io.*;import java.net.Socket;public class TestClient {//客户端    //这是一个main方法,是程序的入口:    public static void main(String[] args) throws IOException {        //1.创建套接字:指定服务器的ip和端口号:        Socket s = new Socket("192.168.199.217",8888);        //2.对于程序员来说,向外发送数据 感受 --》利用输出流:        OutputStream os = s.getOutputStream();        DataOutputStream dos = new DataOutputStream(os);        //利用这个OutputStream就可以向外发送数据了,但是没有直接发送String的方法        //所以我们又在OutputStream外面套了一个处理流:DataOutputStream        dos.writeUTF("你好");        //接收服务器端的回话--》利用输入流:        InputStream is = s.getInputStream();        DataInputStream dis = new DataInputStream(is);        String str = dis.readUTF();        System.out.println("服务器端对我说:"+str);        //3.关闭流  +  关闭网络资源:        dis.close();        is.close();        dos.close();        os.close();        s.close();    }}

服务器端:

import java.io.*;import java.net.ServerSocket;import java.net.Socket;public class TestServer {//服务器    //这是一个main方法,是程序的入口:    public static void main(String[] args) throws IOException {        //1.创建套接字: 指定服务器的端口号        ServerSocket ss = new ServerSocket(8888);        //2.等着客户端发来的信息:        Socket s = ss.accept();//阻塞方法:等待接收客户端的数据,什么时候接收到数据,什么时候程序继续向下执行。        //accept()返回值为一个Socket,这个Socket其实就是客户端的Socket        //接到这个Socket以后,客户端和服务器才真正产生了连接,才真正可以通信了        //3.感受到的操作流:        InputStream is = s.getInputStream();        DataInputStream dis = new DataInputStream(is);        //4.读取客户端发来的数据:        String str = dis.readUTF();        System.out.println("客户端发来的数据为:"+str);        //向客户端输出一句话:---》操作流---》输出流        OutputStream os = s.getOutputStream();        DataOutputStream dos = new DataOutputStream(os);        dos.writeUTF("你好,我是服务器端,我接受到你的请求了");        //5.关闭流+关闭网络资源:        dos.close();        os.close();        dis.close();        is.close();        s.close();        ss.close();    }}

注意:关闭防火墙

三、对象流传送

封装的User类:

import java.io.Serializable;public class User implements Serializable {    private static final long serialVersionUID = 9050691344308365540L;    private String name;    private String pwd;    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public String getPwd() {        return pwd;    }    public void setPwd(String pwd) {        this.pwd = pwd;    }    public User(String name, String pwd) {        this.name = name;        this.pwd = pwd;    }}

客户端:

import java.io.*;import java.net.Socket;import java.util.Scanner;public class TestClient {//客户端    //这是一个main方法,是程序的入口:    public static void main(String[] args) throws IOException {        //1.创建套接字:指定服务器的ip和端口号:        Socket s = new Socket("192.168.199.217",8888);        //录入用户的账号和密码:        Scanner sc = new Scanner(System.in);        System.out.println("请录入您的账号:");        String name = sc.next();        System.out.println("请录入您的密码:");        String pwd = sc.next();        //将账号和密码封装为一个User的对象:        User user = new User(name,pwd);        //2.对于程序员来说,向外发送数据 感受 --》利用输出流:        OutputStream os = s.getOutputStream();        ObjectOutputStream oos = new ObjectOutputStream(os);        oos.writeObject(user);        //接收服务器端的回话--》利用输入流:        InputStream is = s.getInputStream();        DataInputStream dis = new DataInputStream(is);        boolean b = dis.readBoolean();        if(b){            System.out.println("恭喜,登录成功");        }else{            System.out.println("对不起,登录失败");        }        //3.关闭流  +  关闭网络资源:        dis.close();        is.close();        oos.close();        os.close();        s.close();    }}

服务器:

import java.io.*;import java.net.ServerSocket;import java.net.Socket;public class TestServer {//服务器    //这是一个main方法,是程序的入口:    public static void main(String[] args) throws IOException, ClassNotFoundException {        //1.创建套接字: 指定服务器的端口号        ServerSocket ss = new ServerSocket(8888);        //2.等着客户端发来的信息:        Socket s = ss.accept();//阻塞方法:等待接收客户端的数据,什么时候接收到数据,什么时候程序继续向下执行。        //accept()返回值为一个Socket,这个Socket其实就是客户端的Socket        //接到这个Socket以后,客户端和服务器才真正产生了连接,才真正可以通信了        //3.感受到的操作流:        InputStream is = s.getInputStream();        ObjectInputStream ois = new ObjectInputStream(is);        //4.读取客户端发来的数据:        User user = (User)(ois.readObject());        //对对象进行验证:        boolean flag = false;        if(user.getName().equals("娜娜")&&user.getPwd().equals("123123")){            flag = true;        }        //向客户端输出结果:---》操作流---》输出流        OutputStream os = s.getOutputStream();        DataOutputStream dos = new DataOutputStream(os);        dos.writeBoolean(flag);        //5.关闭流+关闭网络资源:        dos.close();        os.close();        ois.close();        is.close();        s.close();        ss.close();    }}

四、加入完整的处理异常方式

服务器端:

import java.io.*;import java.net.ServerSocket;import java.net.Socket;public class TestServer {//服务器    //这是一个main方法,是程序的入口:    public static void main(String[] args) {        //1.创建套接字: 指定服务器的端口号        ServerSocket ss = null;        Socket s = null;        InputStream is = null;        ObjectInputStream ois = null;        OutputStream os = null;        DataOutputStream dos = null;        try {            ss = new ServerSocket(8888);            //2.等着客户端发来的信息:            s = ss.accept();//阻塞方法:等待接收客户端的数据,什么时候接收到数据,什么时候程序继续向下执行。            //accept()返回值为一个Socket,这个Socket其实就是客户端的Socket            //接到这个Socket以后,客户端和服务器才真正产生了连接,才真正可以通信了            //3.感受到的操作流:            is = s.getInputStream();            ois = new ObjectInputStream(is);            //4.读取客户端发来的数据:            User user = (User)(ois.readObject());            //对对象进行验证:            boolean flag = false;            if(user.getName().equals("娜娜")&&user.getPwd().equals("123123")){                flag = true;            }            //向客户端输出结果:---》操作流---》输出流            os = s.getOutputStream();            dos = new DataOutputStream(os);            dos.writeBoolean(flag);        } catch (IOException | ClassNotFoundException e) {            e.printStackTrace();        } finally {            //5.关闭流+关闭网络资源:            try {                if(dos!=null){                    dos.close();                }            } catch (IOException e) {                e.printStackTrace();            }            try {                if(os!=null){                    os.close();                }            } catch (IOException e) {                e.printStackTrace();            }            try {                if(ois!=null){                    ois.close();                }            } catch (IOException e) {                e.printStackTrace();            }            try {                if(is!=null){                    is.close();                }            } catch (IOException e) {                e.printStackTrace();            }            try {                if(s!=null){                    s.close();                }            } catch (IOException e) {                e.printStackTrace();            }            try {                if(ss!=null){                    ss.close();                }            } catch (IOException e) {                e.printStackTrace();            }        }                    }}

客户端:

import java.io.*;import java.net.Socket;import java.util.Scanner;public class TestClient {//客户端    //这是一个main方法,是程序的入口:    public static void main(String[] args){        //1.创建套接字:指定服务器的ip和端口号:        Socket s = null;        OutputStream os = null;        ObjectOutputStream oos = null;        InputStream is = null;        DataInputStream dis = null;        try {            s = new Socket("192.168.199.217",8888);            //录入用户的账号和密码:            Scanner sc = new Scanner(System.in);            System.out.println("请录入您的账号:");            String name = sc.next();            System.out.println("请录入您的密码:");            String pwd = sc.next();            //将账号和密码封装为一个User的对象:            User user = new User(name,pwd);            //2.对于程序员来说,向外发送数据 感受 --》利用输出流:            os = s.getOutputStream();            oos = new ObjectOutputStream(os);            oos.writeObject(user);            //接收服务器端的回话--》利用输入流:            is = s.getInputStream();            dis = new DataInputStream(is);            boolean b = dis.readBoolean();            if(b){                System.out.println("恭喜,登录成功");            }else{                System.out.println("对不起,登录失败");            }        } catch (IOException e) {            e.printStackTrace();        } finally{            //3.关闭流  +  关闭网络资源:            try {                if(dis!=null){                    dis.close();                }            } catch (IOException e) {                e.printStackTrace();            }            try {                if(is!=null){                    is.close();                }            } catch (IOException e) {                e.printStackTrace();            }            try {                if(oos!=null){                    oos.close();                }            } catch (IOException e) {                e.printStackTrace();            }            try {                if(os!=null){                    os.close();                }            } catch (IOException e) {                e.printStackTrace();            }            try {                if(s!=null){                    s.close();                }            } catch (IOException e) {                e.printStackTrace();            }        }    }}

五、多线程接收用户请求

问题:

服务器针对一个请求服务,之后服务器就关闭了(程序自然结束了)

需要解决:

服务器必须一直在监听 ,一直开着,等待客户端的请求 在当前代码中,客户端不用动了

更改服务器代码:

服务器线程:

import java.io.*;import java.net.Socket;public class ServerThread extends Thread {//线程:专门处理客户端的请求    InputStream is = null;    ObjectInputStream ois = null;    OutputStream os = null;    DataOutputStream dos = null;    Socket s = null;    public ServerThread(Socket s){        this.s = s;    }    @Override    public void run() {        try{            //2.等着客户端发来的信息:            is = s.getInputStream();            ois = new ObjectInputStream(is);            //4.读取客户端发来的数据:            User user = (User)(ois.readObject());            //对对象进行验证:            boolean flag = false;            if(user.getName().equals("娜娜")&&user.getPwd().equals("123123")){                flag = true;            }            //向客户端输出结果:---》操作流---》输出流            os = s.getOutputStream();            dos = new DataOutputStream(os);            dos.writeBoolean(flag);        }catch (IOException | ClassNotFoundException e) {            e.printStackTrace();        }finally {            try {                if(dos!=null){                    dos.close();                }            } catch (IOException e) {                e.printStackTrace();            }            try {                if(os!=null){                    os.close();                }            } catch (IOException e) {                e.printStackTrace();            }            try {                if(ois!=null){                    ois.close();                }            } catch (IOException e) {                e.printStackTrace();            }            try {                if(is!=null){                    is.close();                }            } catch (IOException e) {                e.printStackTrace();            }        }    }}

服务器端:

import java.io.*;import java.net.ServerSocket;import java.net.Socket;public class TestServer {//服务器    //这是一个main方法,是程序的入口:    public static void main(String[] args) {        System.out.println("服务器启动了");        //1.创建套接字: 指定服务器的端口号        ServerSocket ss = null;        Socket s = null;        int count = 0;//定义一个计数器,用来计数  客户端的请求        try {            ss = new ServerSocket(8888);            while(true){//加入死循环,服务器一直监听客户端是否发送数据                s = ss.accept();//阻塞方法:等待接收客户端的数据,什么时候接收到数据,什么时候程序继续向下执行。                //每次过来的客户端的请求 靠 线程处理:                new ServerThread(s).start();                count++;                //输入请求的客户端的信息:                System.out.println("当前是第"+count+"个用户访问我们的服务器,对应的用户是:"+s.getInetAddress());            }        } catch (IOException  e) {            e.printStackTrace();        }    }}

到此这篇关于Java网络编程之基于TCP协议的文章就介绍到这了,更多相关Java基于TCP的网络编程内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

在乎的应该是沿途的风景以及看风景的心情。

Java网络编程之基于TCP协议

相关文章:

你感兴趣的文章:

标签云: