Java--网络编程--TCP实现聊天与文件上传

Java–网络编程–TCP实现聊天与文件上传

TCP聊天

服务端

package com.zy.net;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 *description: Java--网络编程--TCP服务端
 *@program: 基础语法
 *@author: zy
 *@create: 2023-03-07 21:23
 */
public class StudyTcpServer {

    public static void main(String[] args) {
        initTcpServer();
    }

    /**
     * @Description 服务端初始化
     * @author zy
     * []
     * void
     * @date 2023-3-7 21:26
     */
    public static void initTcpServer(){
        ServerSocket serverSocket = null;
        Socket accept = null;
        InputStream is = null;
        ByteArrayOutputStream baos = null;
        try {
            // 1.创建一个地址
            serverSocket = new ServerSocket(9999);
            // 2.等待客户端连接
            accept = serverSocket.accept();
            // 3.读取客户端消息
            is = accept.getInputStream();

            // 不建议的写法:当长度超出1024则乱码
            /*byte[] buffer = new byte[1024];
            int len;
            while ((len = is.read(buffer)) != -1){
                String msg = new String(buffer, 0, len);
                System.out.println(msg);
            }*/

            // 管道流接收消息:无论如何都不会乱码
            baos = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len;
            while ((len = is.read(buffer)) != -1){
                baos.write(buffer,0,len);
            }
            System.out.println(baos.toString());

        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                // 4.关闭资源:先开后关
                if (baos != null){
                    baos.close();
                }
                if (is != null){
                    is.close();
                }
                if (accept != null){
                    accept.close();
                }
                if (serverSocket != null){
                    serverSocket.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

客户端

package com.zy.net;

import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;

/**
 *description: Java--网络编程--TCP客户端
 *@program: 基础语法
 *@author: zy
 *@create: 2023-03-07 21:23
 */
public class StudyTcpClient {

    public static void main(String[] args) {
        initTcpClient();
    }

    /**
     * @Description 客户端初始化
     * @author zy
     * []
     * void
     * @date 2023-3-7 21:26
     */
    public static void initTcpClient(){
        Socket socket = null;
        OutputStream os = null;
        try {
            // 1.要知道服务器的地址,端口号
            InetAddress serverIP = InetAddress.getByName("127.0.0.1");
            int port = 9999;
            // 2.创建一个socket连接
            socket = new Socket(serverIP,port);
            // 3.发送消息 IO流
            os = socket.getOutputStream();
            os.write("你好,这里是客户端".getBytes());

        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                // 4.关闭资源:先开后关
                if(os != null){
                    os.close();
                }
                if(socket != null){
                    socket.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

TCP文件上传

服务端

package com.zy.net;

import javax.imageio.stream.FileImageOutputStream;
import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 *description: Java--网络编程--TCP文件上传服务端
 *@program: 基础语法
 *@author: zy
 *@create: 2023-03-07 22:11
 */
public class StudyTcpFileServer {

    public static void main(String[] args) {
        try {
            initTcpFileServer();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void initTcpFileServer() throws Exception {
        // 创建服务端
        ServerSocket serverSocket = new ServerSocket(8888);
        // 监听客户端:阻塞式监听,会一直等待客户端连接
        Socket accept = serverSocket.accept();
        // 获取输入流
        InputStream is = accept.getInputStream();
        // 管道流输出文件
        byte[] buffer = new byte[1024];
        int len;
        FileImageOutputStream fios = new FileImageOutputStream(new File("JavaProjectDemo/statics/netimg/receiveTwo.jpg"));
        while((len = is.read(buffer)) != -1){
            fios.write(buffer,0,len);
        }

        // 通知客户端已接收完毕
        OutputStream os = accept.getOutputStream();
        os.write("已接收完毕!".getBytes());

        // 关闭资源:先开后关
        os.close();
        fios.close();
        is.close();
        accept.close();
        serverSocket.close();
    }
}

客户端

package com.zy.net;

import javax.imageio.stream.FileImageInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;

/**
 *description: Java--网络编程--TCP文件上传客户端
 *@program: 基础语法
 *@author: zy
 *@create: 2023-03-07 22:11
 */
public class StudyTcpFileClient {

    public static void main(String[] args) {
        try {
            initTcpFileClient();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void initTcpFileClient() throws Exception {
        // 得到服务端的地址
        InetAddress serverIP = InetAddress.getByName("127.0.0.1");
        int port = 8888;
        // 创建客户端连接
        Socket socket = new Socket(serverIP,port);
        // 获取输出流
        OutputStream os = socket.getOutputStream();
        // 读取文件为文件流
        FileImageInputStream fiis = new FileImageInputStream(new File("JavaProjectDemo/statics/netimg/one.jpg"));
        // 写出文件
        byte[] buffer = new byte[1024];
        int len;
        while((len = fiis.read(buffer)) != -1){
            os.write(buffer,0,len);
        }

        // 通知服务端,传输完毕
        socket.shutdownOutput();

        // 确定服务端接收完毕,才能断开连接
        InputStream is = socket.getInputStream();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] buffer2 = new byte[1024];
        int len2;
        while ((len2 = is.read(buffer2)) != -1){
            baos.write(buffer2,0,len2);
        }
        System.out.println(baos.toString());

        // 关闭资源:先开后关
        baos.close();
        is.close();
        fiis.close();
        os.close();
        socket.close();
    }
}

Dimension ss = Toolkit.getDefaultToolkit().getScreenSize(); public ChatClient(){ super("登录聊天室"); pnlLogin = new JPanel(); this.getContentPane().add(pnlLogin); lblServer = new JLabel("服务器:"); lblPort = new JLabel("端口:"); lblName = new JLabel("用户名:"); lblPassword = new JLabel("口 令:"); tfServer = new JTextField(15); tfServer.setText("127.0.0.1"); tfPort = new JTextField(6); tfPort.setText("8000"); tfName = new JTextField(20); pwd = new JPasswordField(20); btnLogin = new JButton("登录"); btnRegister = new JButton("注册"); btnExit=new JButton("退出"); pnlLogin.setLayout(null); pnlLogin.setBackground(new Color(205,112,159)); lblServer.setBounds(40,35,50,30); tfServer.setBounds(90,35,102,25); lblPort.setBounds(195,35,35,30); tfPort.setBounds(230,35,55,25); lblName.setBounds(40,70,50,30); tfName.setBounds(90,70,195,25); lblPassword.setBounds(40,100,50,30); pwd.setBounds(90,100,195,25); btnLogin.setBounds(30,160,70,25); btnRegister.setBounds(130,160,70,25); btnExit.setBounds(230,160,70,25); pnlLogin.add(lblServer); pnlLogin.add(tfServer); pnlLogin.add(lblPort); pnlLogin.add(tfPort); pnlLogin.add(lblName); pnlLogin.add(tfName); pnlLogin.add(lblPassword); pnlLogin.add(pwd); pnlLogin.add(btnLogin); pnlLogin.add(btnRegister); pnlLogin.add(btnExit); //设置登录窗口 setResizable(false); setSize(320,260); setVisible(true); setLocation((ss.width-getWidth())/2,(ss.height-getHeight())/2); //为按钮注册监听 btnLogin.addActionListener(this); btnRegister.addActionListener(this); btnExit.addActionListener(this); addWindowListener(new WindowAdapter(){ public void windowClosing(WindowEvent e){ System.exit(0); } }); } //按钮监听响应 public void actionPerformed(ActionEvent ae){ Object source = ae.getSource(); if (source.equals(btnLogin)){ if (tfName.getText().equals("") || pwd.getPassword().equals("")) JOptionPane.showMessageDialog(null, "用户名或密码不能为空"); else strServerIp = tfServer.getText(); login(); } if (source.equals(btnRegister)){ strServerIp = tfServer.getText(); this.dispose(); new Register(strServerIp,8000); } if (source == btnExit) { System.exit(0); } } public void login() { User data = new User(); data.name = tfName.getText(); data.password = new String(pwd.getPassword()); try { String str = InetAddress.getLocalHost().toString(); data.ip = " "+ str.substring(str.lastIndexOf("/"), str.length()); } catch (UnknownHostException ex) { Logger.getLogger(ChatClient.class.getName()).log(Level.SEVERE, null, ex); } try{ Socket sock = new Socket(strServerIp,8000); ObjectOutputStream os = new ObjectOutputStream(sock.getOutputStream()); os.writeObject((User) data); //读来自服务器socket的登录状态 BufferedReader br = new BufferedReader(new InputStreamReader(sock.getInputStream())); String status = br.readLine(); if (status.equals("登陆成功")){ new ChatRoom((String)data.name,strServerIp); this.dispose(); //关闭流对象 os.close(); br.close(); sock.close(); } else{ JOptionPane.showMessageDialog(null, status); os.close(); br.close(); sock.close(); } } catch (ConnectException e1){ JOptionPane.showMessageDialog(null, "连接到制定服务器失败!"); } catch (InvalidClassException e2) { JOptionPane.showMessageDialog(null, "类错误!"); } catch (NotSerializableException e3) { JOptionPane.showMessageDialog(null, "对象未序列化!"); } catch (IOException e4) { JOptionPane.showMessageDialog(null, "不能写入到指定服务器!"); } } public static void main(String arg[]){ new ChatClient(); } }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值