Java网络编程--TCP编程

TCP特点

TCP是面向连接的,传输数据安全,稳定,效率相对较低。

TCP编程基本套路

先创建服务器

创建服务器步骤
1. 指定端口 使用ServerSocket创建服务器
2. 阻塞式等待连接 accept
3. 操作:输入输出流操作
4. 释放资源

import java.io.DataInputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
    public static void main(String[] args) throws IOException {
        System.out.println("--------服务器-----------");
        //1.指定端口 使用ServerSocket创建服务器
        ServerSocket sever=new ServerSocket(8888);//传入端口号
        // 2.阻塞式等待连接 accept
        Socket client=sever.accept();
        System.out.println("一个客户端建立连接");
        //3.操作:输入输出流操作
        DataInputStream dis=new DataInputStream(client.getInputStream());
                //接收客户端数据数据
        String data=dis.readUTF();
        System.out.println(data);
        // 4.释放资源
        dis.close();//关闭流
        client.close();//关闭连接

        sever.close();//关闭服务器
    }
}

创建客户端

创建客户端步骤
1. 建立连接 使用Socket创建客户端+服务器地址和端口
2. 操作:输入输出流操作
3. 释放资源

import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
public class Clipent {
    public static void main(String[] args) throws IOException {
        System.out.println("--------客户端-----------");
        //1.建立连接 使用Socket创建客户端+服务器地址和端口
        Socket client=new Socket("localhost",8888);//传入要连接的服务器地址和端口
        //2.操作:输入输出流操作 推荐使用 DataOutputStream
        DataOutputStream dos=new DataOutputStream(client.getOutputStream());
        String data="666";
        dos.writeUTF(data);
        dos.flush();//刷新流
        //3.释放资源
        dos.close();//关闭流
        client.close();//关闭客户端
    }
}

使用TCP编程实现一个单向的登录功能

创建服务器
import java.io.DataInputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class LoginServer {
    public static void main(String[] args) throws IOException {
        System.out.println("--------服务器-----------");
        //1.指定端口 使用ServerSocket创建服务器
        ServerSocket sever=new ServerSocket(8888);//传入端口号
        // 2.阻塞式等待连接 accept
        Socket client=sever.accept();
        System.out.println("一个客户端建立连接");
        //3.操作:输入输出流操作
        DataInputStream dis=new DataInputStream(client.getInputStream());
        //接收客户端数据数据
        String datas=dis.readUTF();
          //分析数据  .split()方法进行字符串分割
        String[] dataArray=datas.split("&");
        for(String info:dataArray){
            System.out.println(info);
        }
        // 4.释放资源
        dis.close();//关闭流
        client.close();//关闭连接

        sever.close();//关闭服务器
    }
}

创建客户端
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
public class LoginClioent {
    public static void main(String[] args) throws IOException {
        System.out.println("--------客户端-----------");
        BufferedReader console=new BufferedReader(new InputStreamReader(System.in));//输入
        System.out.println("请输入用户名:");
        String uname=console.readLine();
        System.out.println("请输入密码:");
        String upwd=console.readLine();
        //1.建立连接 使用Socket创建客户端+服务器地址和端口
        Socket client=new Socket("localhost",8888);//传入要连接的服务器地址和端口
        //2.操作:输入输出流操作 推荐使用 DataOutputStream
        DataOutputStream dos=new DataOutputStream(client.getOutputStream());
        dos.writeUTF("用户名:"+uname+"&"+"密码:"+upwd);
        dos.flush();//刷新流
        //3.释放资源
        dos.close();//关闭流
        client.close();//关闭客户端
    }
}
运行结果

当客户端输入用户名和密码在服务器端会显示用户输入的用户名和密码

使用TCP编程实现一个双向的登录功能

创建服务器
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class LoginTwoWayServer {
    public static void main(String[] args) throws IOException {
        System.out.println("--------服务器-----------");
        //1.指定端口 使用ServerSocket创建服务器
        ServerSocket sever=new ServerSocket(8888);//传入端口号
        // 2.阻塞式等待连接 accept
        Socket client=sever.accept();
        System.out.println("一个客户端建立连接");
        //3.操作:输入输出流操作
        DataInputStream dis=new DataInputStream(client.getInputStream());
        //接收客户端数据数据
        String datas=dis.readUTF();
        String uname="";
        String upwd="";
        //分析数据  .split()方法进行字符串分割
        String[] dataArray=datas.split("&");
        for(String info:dataArray){
           String[] userinfo=info.split("=");
           if(userinfo[0].equals("用户名")){
               System.out.println("你输入的用户名为:"+userinfo[1]);
               uname=userinfo[1];
           }
            if(userinfo[0].equals("密码")){
                System.out.println("你输入的密码为:"+userinfo[1]);
                upwd=userinfo[1];
            }
        }
        //判断输入用户名密码是否正确并输出结果
        DataOutputStream dos=new DataOutputStream(client.getOutputStream());
        if(uname.equals("张三")&&upwd.equals("123")){
            dos.writeUTF("登录成功!");
        }else {
            dos.writeUTF("用户名或者密码错误!");
        }
        dos.flush();//刷新流
        // 4.释放资源
        dis.close();//关闭流
        client.close();//关闭连接

        sever.close();//关闭服务器
    }
}

创建客户端
import java.io.*;
import java.net.Socket;

public class LoginTwoWayClioent {
    public static void main(String[] args) throws IOException {
        System.out.println("--------客户端-----------");
        BufferedReader console=new BufferedReader(new InputStreamReader(System.in));//输入
        System.out.println("请输入用户名:");
        String uname=console.readLine();
        System.out.println("请输入密码:");
        String upwd=console.readLine();
        //1.建立连接 使用Socket创建客户端+服务器地址和端口
        Socket client=new Socket("localhost",8888);//传入要连接的服务器地址和端口
        //2.操作:输入输出流操作 推荐使用 DataOutputStream
        DataOutputStream dos=new DataOutputStream(client.getOutputStream());
        dos.writeUTF("用户名="+uname+"&"+"密码="+upwd);
        dos.flush();//刷新流

            //接收服务器端返回数据数据
            DataInputStream dis=new DataInputStream(client.getInputStream());
            String result=dis.readUTF();
            System.out.println(result);
        //3.释放资源
        dos.close();//关闭流
        client.close();//关闭客户端
    }
}

运行结果

客户端输入用户名和密码服务器端进行判断用户输入的用户名或者密码是否正确并返回给客户端

TCP编程实现多用户登录

创建服务器

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
/**
 * 模拟多个客户端登录
 */
public class LoginMultiWayServer {
    public static void main(String[] args) throws IOException {
        System.out.println("--------服务器-----------");
        boolean isRunning=true;
        //1.指定端口 使用ServerSocket创建服务器
        ServerSocket sever=new ServerSocket(8888);//传入端口号
        // 2.阻塞式等待连接 accept
        while (isRunning){
            Socket client=sever.accept();
            System.out.println("一个客户端建立连接");
            new Thread(new Channel(client)).start();
        }
        sever.close();//关闭服务器
    }
   static class Channel implements Runnable{
        private Socket client;
        //输入流
        private DataInputStream dis;
        //输出流
        private DataOutputStream dos;
        public Channel(Socket client){
            this.client=client;
            try {
                //输入流
                dis=new DataInputStream(client.getInputStream());
                //输出流
                dos=new DataOutputStream(client.getOutputStream());
            } catch (IOException e) {
                e.printStackTrace();
                release();
            }
        }
       //接收数据方法
       private String receive(){
           //接收客户端数据数据
           String datas= null;
           try {
               datas = dis.readUTF();
           } catch (IOException e) {
               e.printStackTrace();
           }
           return  datas;
       }
       //释放资源
       private void release(){
           try {
               if (null!=dos){
                   dos.close();//关闭流
               }
           } catch (IOException e) {
               e.printStackTrace();
           }
           try {
               if (null!=dis){
                   dis.close();//关闭流
               }
           } catch (IOException e) {
               e.printStackTrace();
           }
           try {
               if(null!=client){
                   client.close();//关闭连接
               }
           } catch (IOException e) {
               e.printStackTrace();
           }
       }
       //发送数据方法
       private void send(String msg){
           try {
               dos.writeUTF(msg);
               dos.flush();//刷新流
           } catch (IOException e) {
               e.printStackTrace();
           }

       }
        @Override
        public void run() {
            //3.操作:输入输出流操作
            String uname="";
            String upwd="";
            //分析数据  .split()方法进行字符串分割
            String[] dataArray=receive().split("&");
            for(String info:dataArray){
                String[] userinfo=info.split("=");
                if(userinfo[0].equals("用户名")){
                    System.out.println("你输入的用户名为:"+userinfo[1]);
                    uname=userinfo[1];
                }
                if(userinfo[0].equals("密码")){
                    System.out.println("你输入的密码为:"+userinfo[1]);
                    upwd=userinfo[1];
                }
            }
            //判断输入用户名密码是否正确并输出结果

            if(uname.equals("张三")&&upwd.equals("123")){
                send("登录成功!");
            }else {
                send("用户名或者密码错误!");
            }

            // 4.释放资源
            release();
        }

    }

}

创建客户端

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

/**
 * 模拟多个客户端登录
 */
public class LoginMultiWayClioent {
    public static void main(String[] args) throws IOException {
        System.out.println("--------客户端-----------");
        BufferedReader console=new BufferedReader(new InputStreamReader(System.in));//输入
        System.out.println("请输入用户名:");
        String uname=console.readLine();
        System.out.println("请输入密码:");
        String upwd=console.readLine();
        //1.建立连接 使用Socket创建客户端+服务器地址和端口
        Socket client=new Socket("localhost",8888);//传入要连接的服务器地址和端口
        //2.操作:输入输出流操作 推荐使用 DataOutputStream
        DataOutputStream dos=new DataOutputStream(client.getOutputStream());
        dos.writeUTF("用户名="+uname+"&"+"密码="+upwd);
        dos.flush();//刷新流

            //接收服务器端返回数据数据
            DataInputStream dis=new DataInputStream(client.getInputStream());
            String result=dis.readUTF();
            System.out.println(result);
        //3.释放资源
        dos.close();//关闭流
        client.close();//关闭客户端
    }
}
客户端代码优化

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

/**
 * 模拟多个客户端登录
 */
public class LoginMultiWayClioent {
    public static void main(String[] args) throws IOException {
        System.out.println("--------客户端-----------");
        BufferedReader console=new BufferedReader(new InputStreamReader(System.in));//输入
        System.out.println("请输入用户名:");
        String uname=console.readLine();
        System.out.println("请输入密码:");
        String upwd=console.readLine();
        //1.建立连接 使用Socket创建客户端+服务器地址和端口
        Socket client=new Socket("localhost",8888);//传入要连接的服务器地址和端口
        //2.操作:输入输出流操作 推荐使用 DataOutputStream
            new Send(client).send("用户名="+uname+"&"+"密码="+upwd);
            //接收服务器端返回数据数据
            new Receive(client).receive();
        //3.释放资源
        client.close();//关闭客户端
    }
    //发送
    static class Send{
        private Socket client;
        private DataOutputStream dos;
        public Send(Socket client){
            this.client=client;
            try {
                dos=new DataOutputStream(client.getOutputStream());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        public void send(String msg){
            try {
                dos.writeUTF(msg);
                dos.flush();//刷新流
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    //接收
    static class Receive{
        private Socket client;
        private DataInputStream dis;
        public Receive(Socket client){
            this.client=client;
            try {
                dis=new DataInputStream(client.getInputStream());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        public void receive(){
            String result= null;
            try {
                result = dis.readUTF();
                System.out.println(result);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

TCP编程实现文件上传

创建服务器

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

public class FileServer {
    public static void main(String[] args) throws IOException {
        System.out.println("--------服务器-----------");
        //1.指定端口 使用ServerSocket创建服务器
        ServerSocket sever=new ServerSocket(8888);//传入端口号
        // 2.阻塞式等待连接 accept
        Socket client=sever.accept();
        System.out.println("一个客户端建立连接");
        //3.操作:文件 拷贝存储
        InputStream is=new BufferedInputStream(client.getInputStream());
        OutputStream os=new BufferedOutputStream(new FileOutputStream("xxxx"));//传入文件上传地址
        byte[] flush=new byte[1024];
        int index=-1;
        while ((index=is.read(flush))!=-1){
            os.write(flush,0,index);
        }
        os.flush();
        //4.释放资源
        os.close();
        is.close();
        client.close();//关闭连接

        sever.close();//关闭服务器
    }
}

创建客户端

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

public class FileClioent {
    public static void main(String[] args) throws IOException {
        System.out.println("--------客户端-----------");
        //1.建立连接 使用Socket创建客户端+服务器地址和端口
        Socket client=new Socket("localhost",8888);//传入要连接的服务器地址和端口
        //2.操作:文件拷贝 上传
        InputStream is=new BufferedInputStream(new FileInputStream("xxxx"));//传入文件地址
        OutputStream os=new BufferedOutputStream(client.getOutputStream());
        byte[] flush=new byte[1024];
        int index=-1;
        while ((index=is.read(flush))!=-1){
            os.write(flush,0,index);
        }
        os.flush();
        //3.释放资源
        os.close();
        is.close();
        client.close();//关闭客户端
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值