首页 > 其他分享 >Tcp通信

Tcp通信

时间:2022-09-02 02:22:44浏览次数:51  
标签:java socket 通信 Tcp new msg import Socket

image

一发一收

Client

package tcpDemo;

import java.io.OutputStream;
import java.io.PrintStream;
import java.net.Socket;
import java.util.Scanner;

public class Client {
    public static void main(String[] args) throws Exception {
        //1.创建Socke通信管道请求服务端的连接
        //public Socket(String host, int port)
        //参数一: 服务端的IP地址
        //参数二: 服务端的端口
        Socket socket = new Socket("127.0.0.1",7777);
        //2, 从socket通信管道中得到一个字节输出流 负责发送数据
        OutputStream os = socket.getOutputStream();
        //3,把低级的字节流打包成打印流
        PrintStream ps = new PrintStream(os);
        Scanner sc = new Scanner(System.in);
        String msg = "";
        while(true) {
            msg = sc.nextLine();
            if(msg.equals("exit")) {
                System.out.println("聊天结束");
                socket.close();
            }
            ps.println(msg);
            ps.flush();
        }
    }
}

Server

package tcpDemo;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {
    public static void main(String[] args) throws Exception {
        //1.注册端口
        ServerSocket serverSocket = new ServerSocket(7777);
        //2.必须调用accept方法,等待接收客户端的Socket连接请求,建立Socket通信管道
        Socket socket = serverSocket.accept();
        //3, 从socket通信管道中得到一个字节输入流
        InputStream is = socket.getInputStream();
        //4. 把字节输入流包装成缓冲字符输入流进行消息的接收
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        //5. 按照行读取消息
        String msg;
        while((msg = br.readLine()) != null) {
            System.out.println(socket.getRemoteSocketAddress() + "说了: " + msg);
        }
    }
}

image

多发多收

client

package tcpDemo;

import java.io.OutputStream;
import java.io.PrintStream;
import java.net.Socket;
import java.util.Scanner;

public class Client {
    public static void main(String[] args) throws Exception {
        //1.创建Socke通信管道请求服务端的连接
        //public Socket(String host, int port)
        //参数一: 服务端的IP地址
        //参数二: 服务端的端口
        Socket socket = new Socket("127.0.0.1",7777);
        //2, 从socket通信管道中得到一个字节输出流 负责发送数据
        OutputStream os = socket.getOutputStream();
        //3,把低级的字节流打包成打印流
        PrintStream ps = new PrintStream(os);
        Scanner sc = new Scanner(System.in);
        String msg = "";
        while(true) {
            msg = sc.nextLine();
            if(msg.equals("exit")) {
                System.out.println("聊天结束");
                socket.close();
            }
            ps.println(msg);
            ps.flush();
        }
    }
}

server

package tcpDemo;

import ch.qos.logback.classic.net.server.ServerSocketReceiver;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {
    public static void main(String[] args) throws Exception {
        //1.注册端口
        ServerSocket serverSocket = new ServerSocket(7777);
        //2.必须调用accept方法,等待接收客户端的Socket连接请求,建立Socket通信管道
        while(true) {
            Socket socket = serverSocket.accept();
            new ServerReaderThread(socket).start();
        }

    }
}

包装的Socket类

package tcpDemo;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.Socket;

public class ServerReaderThread extends Thread {
    private Socket socket;
    ServerReaderThread(Socket socket) {
        this.socket = socket;
    }
    @Override
    public void run() {
        try {
            //3, 从socket通信管道中得到一个字节输入流
            InputStream is = this.socket.getInputStream();
            //4. 把字节输入流包装成缓冲字符输入流进行消息的接收
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            //5. 按照行读取消息
            String msg;
            while((msg = br.readLine()) != null) {
                System.out.println(socket.getRemoteSocketAddress() + "说了: " + msg);
            }
        } catch (Exception err) {
            System.out.println(socket.getRemoteSocketAddress() + "下线了");
        }

    }
}

线程池优化

Client

package tcpDemo;

import java.io.OutputStream;
import java.io.PrintStream;
import java.net.Socket;
import java.util.Scanner;

public class Client {
    public static void main(String[] args) throws Exception {
        //1.创建Socke通信管道请求服务端的连接
        //public Socket(String host, int port)
        //参数一: 服务端的IP地址
        //参数二: 服务端的端口
        Socket socket = new Socket("127.0.0.1",7777);
        //2, 从socket通信管道中得到一个字节输出流 负责发送数据
        OutputStream os = socket.getOutputStream();
        //3,把低级的字节流打包成打印流
        PrintStream ps = new PrintStream(os);
        Scanner sc = new Scanner(System.in);
        String msg = "";
        while(true) {
            msg = sc.nextLine();
            if(msg.equals("exit")) {
                System.out.println("聊天结束");
                socket.close();
            }
            ps.println(msg);
            ps.flush();
        }
    }
}

Server

package tcpDemo;

import ch.qos.logback.classic.net.server.ServerSocketReceiver;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.*;

public class Server {
    private static ExecutorService pool = new ThreadPoolExecutor(3,5, 6,TimeUnit.SECONDS,new ArrayBlockingQueue<>(2), Executors.defaultThreadFactory(),new ThreadPoolExecutor.AbortPolicy());
    public static void main(String[] args) throws Exception {
        //1.注册端口
        ServerSocket serverSocket = new ServerSocket(7777);
        //2.必须调用accept方法,等待接收客户端的Socket连接请求,建立Socket通信管道
        while(true) {
            Socket socket = serverSocket.accept();
            Runnable target = new ServerReaderRunnable(socket);
            pool.execute(target);
        }

    }
}

标签:java,socket,通信,Tcp,new,msg,import,Socket
From: https://www.cnblogs.com/guozhiqiang/p/16629584.html

相关文章

  • netstat 查看TCP状态值
     一。TCP状态值netstat-n|awk'/^tcp/{++S[$NF]}END{for(ainS)printa,S[a]}'CLOSED:无连接是活动的或正在进行LISTEN:服务器在等待进入呼叫SYN_RECV:一个连......
  • 【js与native通信】1 通信协议制定
    通过native<-互相调用->js知道WebView有一个方法setWebChromeClient,可以设置WebChromeClient对象。而WebChromeClient对象中有三个方法,分别是onJsAlert......
  • OSI七层模型与TCP/IP协议
    作者:菘蓝时间:2022/9/1========================================================================================================一、为什么网络需要分层1.1层次划......
  • TCP UDP
    无奈被怼了,赶紧梳理一下自己关于tcp和udp所了解的内容TCPTCP是面向连接的传输层协议,可以提供可保的传输服务。而且,TCP提供面向流的全双工通信。TCP在发送数据前需要经过......
  • 网络基础七层模型与TCP/IP协议
    1.网络基础1.1什么是网络网络就是计算机网络是一组计算机或网络设备通过有形的线缆或无形的媒介如无线,连接起来,按照一定的规则,进行通信的集合。网络通信就是指终端设......
  • 【Socket / Grizzly】Grizzly TCP Server & Client
    SimpleTCPServerimportorg.glassfish.grizzly.Connection;importorg.glassfish.grizzly.filterchain.Filter;importorg.glassfish.grizzly.filterchain.FilterChai......
  • OSI模型 TCP/IP协议
    常见术语网络相关的术语1、拓扑:物理拓扑-----体现了设备之间的连接关系逻辑拓扑----设备之间的通信关系2、数据载荷:传递的实际信息3、报文(PDU--协议数据单元)4、......
  • spi通信
    【原创】详细解析FPGA与STM32的SPI通信 SPIperipheral......
  • CH579M以太网控制板-多台控制板使用网线串联连接并作为TCP客户端和TCP服务器通信(和电
    <p><iframename="ifd"src="https://mnifdv.cn/resource/cnblogs/CH579_DTU_PBX"frameborder="0"scrolling="auto"width="100%"height="1500"></iframe></p> 说明......
  • CH579M以太网控制板-单台控制板作为TCP客户端和电脑端的TCP服务器通信(和电脑网线直连
    <p><iframename="ifd"src="https://mnifdv.cn/resource/cnblogs/CH579_DTU_PBX"frameborder="0"scrolling="auto"width="100%"height="1500"></iframe></p> 说明......