java 如何在服务器端用socket创建一个监听端口,并在客户端发送信息

服务端

try {
    ServerSocket serverSocket = new ServerSocket(9000);//建立端口号为9000
    Socket socket = serverSocket.accept();//等待客户端的连接
    InputStream is = socket.getInputStream();//接受客户端的信息流

    //接受信息代码模块
    byte[] buffer = new byte[1024];
    int len;
    while ((len=is.read(buffer))!=-1)
    {
        String msg = new String(buffer, 0, len);
        System.out.println(msg);
    }

} catch (IOException e) {
    e.printStackTrace();
}

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) {
        try {
            ServerSocket serverSocket = new ServerSocket(9000);//建立端口号为9000
            Socket socket = serverSocket.accept();//等待客户端的连接
            InputStream is = socket.getInputStream();//接受客户端的信息流

            //接受信息代码模块
            byte[] buffer = new byte[1024];
            int len;
            while ((len=is.read(buffer))!=-1)
            {
                String msg = new String(buffer, 0, len);
                System.out.println(msg);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

客户端:

public class TcpClient {
    public static void main(String[] args) {
        try {
            InetAddress byName = InetAddress.getByName("127.0.0.1");//ip地址
            int port=9000;//端口号
            Socket socket = new Socket(byName, port);//建立一个socket连接
            OutputStream ou = socket.getOutputStream();//发送io流
            ou.write("你好,李焕英".getBytes(StandardCharsets.UTF_8));//getBytes()是将String字符串转换为Byte数组
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
//客户端
public class TcpClient {
    public static void main(String[] args) {
        try {
            InetAddress byName = InetAddress.getByName("127.0.0.1");//ip地址
            int port=9000;//端口号
            Socket socket = new Socket(byName, port);//建立一个socket连接
            OutputStream ou = socket.getOutputStream();//发送io流
            ou.write("你好,李焕英".getBytes(StandardCharsets.UTF_8));//getBytes()是将String字符串转换为Byte数组
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

先运行服务器端,再运行客户端,运行结果如下:

S:\java\jdk\bin\java.exe -javaagent:S:\java\ideaIU-2020.3.2.win\lib\idea_rt.jar=56092:S:\java\ideaIU-2020.3.2.win\bin -Dfile.encoding=UTF-8 -classpath C:\Users\279186856\Desktop\寒假\java学习\GUI_Study\out\production\GUI_Study com.hu.net.TcpServer
你好,李焕英

猜你喜欢

转载自blog.csdn.net/qq_56728342/article/details/122645648