Java教程

java的TCP通信

本文主要是介绍java的TCP通信,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

客户端

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

public class SendSocket {
    public static void main(String[] args) throws IOException {
        //创建对象
        Socket socket = new Socket(InetAddress.getLocalHost(), 12345);

        //获取输出流
        OutputStream outputStream = socket.getOutputStream();

        //发送数据
        outputStream.write("Tcp我来发送数据了".getBytes());

        //关闭socket
        socket.close();
    }
}


服务端

package mystring.demo2;

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

public class ReviceSocket {
    public static void main(String[] args) throws IOException {
        //创建服务器对象
        ServerSocket serverSocket = new ServerSocket(12345);
        Socket accept = serverSocket.accept();

        //获取输出流
        InputStream inputStream = accept.getInputStream();
        byte[] bytes = new byte[1024];
        int len = inputStream.read(bytes);
        System.out.println(new String(bytes,0,len));
        accept.close();
        serverSocket.close();
    }
}


这篇关于java的TCP通信的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!