JAVA网络编程(2)TCP编程

2.1 需求描述

功能描述:实现类似QQ、微信、邮箱的网络登录功能,可以多个用户同时登录。为了便于理解,进行功能分解迭代、分为一次单向通信、一次双向通信、传输对象、引入多线程来分别实现。

  • 需要分别开发一个客户端程序及一个服务器程序
  • 服务器需要处于开启状态
  • 服务器需要在某个端口监听客户端请求
  • 客户端访问服务器,必须知道服务器的IP及端口

2.2 一次单项通信

//服务器端代码实现
public class LoginServer {

    public static void main(String[] args) throws IOException {
        //开启服务,指定监听端口
        ServerSocket socketServer = new ServerSocket(8080);
        //在等待的接口监听
        Socket socket = socketServer.accept(); //等待客户端连接,没有连接程序在此阻塞
        //接收数据
        InputStream is = socket.getInputStream();
        DataInputStream dis = new DataInputStream(is);
        String s = dis.readUTF();
        System.out.println("用户登录信息:" + s);
        //关闭资源
        dis.close();
        //socket.close(); //不需要手动关闭
        socketServer.close(); //需要手动关闭
    }

}
//客户端代码实现
public class LoginClient {

    public static void main(String[] args) throws IOException {
        //建立socket连接
        Socket socket = new Socket("127.0.0.1",8080);
        //发送数据
        OutputStream os = socket.getOutputStream();
        DataOutputStream dos = new DataOutputStream(os);
        dos.writeUTF("username=fyy&password=123456");
        //关闭连接
        dos.close();
        //socket.close(); //不需要手动关闭
    }

}

2.3 一次双向通信

//服务器端代码实现
public class LoginServer {

    public static void main(String[] args) throws IOException {
        //开启服务,指定监听端口
        ServerSocket socketServer = new ServerSocket(8080);
        //在等待的接口监听
        Socket socket = socketServer.accept(); //等待客户端连接,没有连接程序在此阻塞
        DataInputStream dis = new DataInputStream(socket.getInputStream());
        DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
        //接收数据
        String s = dis.readUTF();
        System.out.println("用户登录信息:" + s);
        //发送数据
        dos.writeUTF("用户登录成功!");
        //关闭资源
        dis.close();
        dos.close();
        //socket.close(); //不需要手动关闭
        socketServer.close(); //需要手动关闭
    }

}
//客户端代码实现
public class LoginClient {

    public static void main(String[] args) throws IOException {
        //建立socket连接
        Socket socket = new Socket("127.0.0.1",8080);
        DataInputStream dis = new DataInputStream(socket.getInputStream());
        DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
        //发送数据
        dos.writeUTF("username=fyy&password=123456");
        String str = dis.readUTF();
        System.out.println("服务器返回数据:" + str);
        //关闭连接
        dos.close();
        dis.close();
        //socket.close(); //不需要手动关闭
    }

}

2.4 一次双向通信,传输对象

//服务器端代码实现
public class LoginServer {

    public static void main(String[] args) throws IOException, ClassNotFoundException {
        //开启服务,指定监听端口
        ServerSocket socketServer = new ServerSocket(8080);
        //在等待的接口监听
        Socket socket = socketServer.accept(); //等待客户端连接,没有连接程序在此阻塞
		ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
        DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
        //接收数据
        User user = (User) ois.readObject();
        System.out.println("用户名:" + user.getUserId());
        System.out.println("密码:" + user.getPassword());
        //响应请求
        if(user.getUserId().equals("admin") && user.getPassword().equals("123")){
            dos.writeUTF("用户登录成功!");
        }else{
            dos.writeUTF("用户名/密码错误!");
        }
        //关闭资源
        ois.close();
        dos.close();
        //socket.close(); //不需要手动关闭
        socketServer.close(); //需要手动关闭
    }

}
//客户端代码实现
public class LoginClient {

    public static void main(String[] args) throws IOException {
        //建立socket连接
        Socket socket = new Socket("127.0.0.1",8080);
        DataInputStream dis = new DataInputStream(socket.getInputStream());
        ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
        //获取键盘输入,封装成User对象
        Scanner input = new Scanner(System.in);
        System.out.println("请输入用户名:");
        String userId = input.next();
        System.out.println("请输入密码:");
        String password = input.next();
        User user = new User(userId,password);
        //发送数据
        oos.writeObject(user);
        //获取返回数据
        String str = dis.readUTF();
        System.out.println("服务器返回数据:" + str);
        //关闭连接
        oos.close();
        dis.close();
        //socket.close(); //不需要手动关闭
    }

}
//封装的User对象
public class User implements Serializable {
    
    private String userId;
    private String password;

    public User(){

    }

    public User(String userId,String password){
        this.userId = userId;
        this.password = password;
    }

    public String getUserId() {
        return userId;
    }

    public void setUserId(String userId) {
        this.userId = userId;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    @Override
    public String toString() {
        return "User{" +
                "userId='" + userId + '\'' +
                ", password='" + password + '\'' +
                '}';
    }
}

2.5 TCP文件上传

//服务器端编码实现
public class UpServer {

    public static void main(String[] args) throws IOException {
        ServerSocket socketServer = new ServerSocket(8088);
        Socket socket = socketServer.accept();
        String dFilePath = "F:\\test2.txt";
        try ( //创建文件输入输出流
              BufferedInputStream bis = new BufferedInputStream(socket.getInputStream());
              BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(dFilePath));
        ){
            //读取文件
            byte[] buf = new byte[1024];
            int len;
            while ((len = bis.read(buf)) != -1){
                bos.write(buf,0,len);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

}
//客户端编码实现
public class UpClient {

    public static void main(String[] args) throws IOException {
        String sFilePath = "F:\\test.txt";
        Socket socket = new Socket("127.0.0.1",8088);
        try ( //创建文件输入输出流
              BufferedInputStream bis = new BufferedInputStream(new FileInputStream(sFilePath));
              BufferedOutputStream bos = new BufferedOutputStream(socket.getOutputStream());
        ){
            //读取文件
            byte[] buf = new byte[1024];
            int len;
            while ((len = bis.read(buf)) != -1){
                bos.write(buf,0,len);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

程序小达人

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值