阅读 1116

java实现TCP通信

1.概述

通过ServerSocket与Socket实现的TCP的通信,这个例子配合了swing使用,其实作者之前发过一篇ServerSocker与Socket的通信,在这里,这边文章就是在这个例子上修改而成的.

其实原理很简单的,就是一个服务端一个客户端,服务端这边创建好ServerSocket后,使用accept()堵塞一直等待客户端发送socket. 好吧,不废话了.进正题.

2.服务端

swing的部分就不说了,说一下主要操作

(1)新建ServerSocket

ServerSocket serverSocket = null;
serverSocket = new ServerSocket(12345);//一个不被占用的端口即可
复制代码

构造方法的参数是端口,默认使用本地ip. ServerSocket有三个构造方法,

ServerSocket(int port);
ServerSocket(int port,int backlog);
ServerSocker(int poer,int backlog,InetAddress ip);
复制代码

详情可以看这里

(2)接收socket

Socket socket = serverSocket.accept();
复制代码

返回一个Socket(),会一直等待,处于阻塞状态. 一般设置一个while(true)循环接收.

(3)数据处理

使用DataInputStream与DataOutputStream:

DataInputStream inputStream = new DataInputStream(socket.getInputStream());
DataOutputStram outputStream = new DataOutputStream(socket.getOutputStream());
复制代码

然后使用read与write方法即可. 注意关闭的时候要等输入输出完成后再一起关闭,就是说,不能这样:

DataInputStream inputStream = new DataInputStream(socket.getInputStream());
String data = inputStream.readUTF();
inputStream.close();
DataOutputStream outputStream = new DataOutputStream(socket.getOutputStream());
outputStream.writeUTF("ok");
outputStream.close();
复制代码

这样的话getInputStream()没有问题,但是到了getOutputStream()的时候就有问题了,会提示异常:

在这里插入图片描述
Socket is closed. 所以解决办法就是等输出完之后再一起关闭:

DataInputStream inputStream = new DataInputStream(socket.getInputStream());
String data = inputStream.readUTF();
DataOutputStream outputStream = new DataOutputStream(socket.getOutputStream());
outputStream.writeUTF("ok");
inputStream.close();//等输出完成后再关闭
outputStream.close();
复制代码

(4)完整代码Server.java

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import javax.swing.*;

public class Server {
    public static void main(String[] args)
    {
        JFrame frame = new JFrame("Server");
        JPanel panel = new JPanel();
        JTextArea text = new JTextArea();

        panel.add(text);
        frame.setContentPane(panel);
        frame.setSize(600, 300);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        ServerSocket serverSocket = null;
        try
        {
            serverSocket = new ServerSocket(12345);
            while (true)
            {
                Socket socket = serverSocket.accept();
                DataInputStream inputStream = new DataInputStream(socket.getInputStream());
                text.setText(inputStream.readUTF());

                DataOutputStream outputStream = new DataOutputStream(socket.getOutputStream());
                outputStream.writeUTF("ok");
                inputStream.close();
                outputStream.close();
                socket.close();
            }
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        finally
        {
            try
            {
                serverSocket.close();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
        }
    }
}
复制代码

3.客户端

客户端的操作就是开启一个Socket,再通过这个socket获取对应的输入输出流就可以了.

(1)新建一个Socket

Socket socket = new Socket("127.0.0.1",12345);//这个端口与服务端的端口对应
复制代码

Socket有三个构造方法:

Socket(InetAddress ip,int port);
Socket(String ip,int port);
Socket(InetAddress ip,int port,InetAddress localIp,int localPort);
Socket(String ip,int port,InetAddress localIp,int localPort);
复制代码

详情可以看这里

(2)输入输出

同样使用DataInputStream与DataOutputStream:

DataOutputStream outputStream = new DataOutputStream(socket.getOutputStream());
DataInputStream inputStream = new DataInputStream(socket.getInputStream());
复制代码

(3)完整代码Client.java

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;

import javax.swing.*;
import java.awt.GridLayout;
public class Client
{
    public static void main(String[] args) {
        JFrame frame = new JFrame();
        JTextArea text = new JTextArea();
        JButton send = new JButton();
        GridLayout layout = new GridLayout(2, 1, 0, 5);

        frame.setTitle("Client");
        frame.setVisible(true);
        frame.setLocationRelativeTo(null);
        frame.setSize(600, 300);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLayout(layout);

        frame.add(text);
        frame.add(send);
        send.setText("send");
        send.addActionListener(v ->
        {
            try
            {
                String host = "127.0.0.1";
                int port = 12345;
                Socket socket = new Socket(host, port);
                DataOutputStream outputStream = new DataOutputStream(socket.getOutputStream());
                outputStream.writeUTF(text.getText());

                DataInputStream inputStream = new DataInputStream(socket.getInputStream());
                text.setText(inputStream.readUTF());
                outputStream.close();
                inputStream.close();
                socket.close();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
        });
    }
}
复制代码

4.测试

先开启服务端,再开启客户端,这里设置了服务端返回给客户端的信息为"ok".

在这里插入图片描述

文章分类
后端
文章标签