TCP实现消息传递

分别实现client和server, 完成消息传递功能

(简易版本, 作为学习记录

client端
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.nio.charset.StandardCharsets;

public class TCPclient {
    public static void main(String[] args) {
        int port = 9999;
        Socket socket = null;
        OutputStream outputStream = null;

        try {
            InetAddress inetAddress = InetAddress.getByName("127.0.0.1");
            socket = new Socket(inetAddress, port);
            outputStream = socket.getOutputStream();
            outputStream.write("oula".getBytes());
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (socket != null){
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(outputStream != null){
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }
}

解释:

  • socket作为链接通道打开指定IP和端口, 需要与服务器端一致
  • 作为socket类包含输出流方法, 用outputstream承接输出流,
  • OutputStream输出字符串的字符流形式到服务端
server端

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

public class TCPServer {
    public static void main(String[] args) {
        int port = 9999;
        ServerSocket serverSocket = null;
        Socket socket = null;
        InputStream inputStream = null;
        ByteArrayOutputStream baos = null;
        try {
            serverSocket = new ServerSocket(port);
            socket = serverSocket.accept();
            inputStream = socket.getInputStream();
            baos = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len;
            while((len = inputStream.read(buffer)) != -1){
                baos.write(buffer, 0, len);
            }
            System.out.println(baos.toString());

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (serverSocket != null){
                try {
                    serverSocket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (socket != null){
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (inputStream != null){
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (baos != null){
                try {
                    baos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

解释

  • 设置serversocket, 指定打开port端口
  • 用accept方法阻塞接收客户端端口的连接请求
  • inputstream承接socket的输入流
  • 因为接收的是字节流, 用ByteArrayOutputStream接收输入进来的字节流(相当于存放输入进来的数据的一个变量)
  • 打印的时候转toString
效果

在这里插入图片描述
服务端接收到并打印了"欧拉"


如果想要按输入的字符串作为传递消息, 该如何实现?
做一些修改即可

client端

import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

public class TCPclient {
    public static void main(String[] args) {
        int port = 9999;
        Socket socket = null;
        OutputStream outputStream = null;

        try {
            InetAddress inetAddress = InetAddress.getByName("127.0.0.1");

            Scanner scanner = new Scanner(System.in);
            System.out.println("input quit to exit");

            while(true){
                socket = new Socket(inetAddress, port);
                outputStream = socket.getOutputStream();

                String message = scanner.next();
                if(message.equals("quit")) break;
                else{
                    outputStream.write(message.getBytes());

                    socket.close();
                    outputStream.close();
                }
            }


        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (socket != null){
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(outputStream != null){
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }
}

server端

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

public class TCPServer {
    public static void main(String[] args) {
        int port = 9999;
        ServerSocket serverSocket = null;
        Socket socket = null;
        InputStream inputStream = null;
        ByteArrayOutputStream baos = null;
        try {

            byte[] buffer = new byte[1024];
            int len;

            while(true){
                serverSocket = new ServerSocket(port);
                socket = serverSocket.accept();
                inputStream = socket.getInputStream();
                baos = new ByteArrayOutputStream();

                while((len = inputStream.read(buffer)) != -1){
                    baos.write(buffer, 0, len);
                }
                System.out.println(baos.toString());

                serverSocket.close();
                socket.close();
                inputStream.close();
                baos.close();
            }


        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (serverSocket != null){
                try {
                    serverSocket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (socket != null){
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (inputStream != null){
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (baos != null){
                try {
                    baos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

采用的是循环建立连接, 每次发一条消息的方式实现, 但是如何在单次连接时发送多条消息还不懂, 思路是服务端需要监听输入流, 有输入时触发一次打印, 但是如何监听输入流, 尚待解决

效果

在这里插入图片描述
在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值