当前位置:网站首页>socket通讯

socket通讯

2022-07-06 09:27:00 帅帅气气的黑猫警长

python发送端

from socket import *
serverName = '*.*.*.*'
serverPort = *
clientSocket =socket(AF_INET,SOCK_STREAM)    # 创建socket

clientSocket.connect((serverName,serverPort))    # 连接

sentence = input('Input->:')    #输入要传输的数据

clientSocket.send(sentence.encode("utf8"))    #向接收端发送

clientSocket.close() #关闭套字节

python接收端

import socket
 
# 创建socket
tcp_server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
 
# 本地信息
address = ('',702)
 
# 绑定
tcp_server_socket.bind(address)
tcp_server_socket.listen(128)
 
print('启动服务器监听')
 
while True:
    # 等待新的客户端连接
    client_socket, clientAddr = tcp_server_socket.accept()
    while True:
        # 接收对方发送过来的数据
        recv_data = client_socket.recv(1024)  # 接收1024个字节
        if recv_data:
            print('接收到的数据为:', recv_data.decode('utf8'))
        else:
            break
    client_socket.close()
 
tcp_server_socket.close()

java接收端

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.ServerSocket;
import java.net.Socket;
 
public class test {
 
	       public static void main(String args[]) throws IOException {
	          //为了简单起见,所有的异常信息都往外抛
	          int port = 702;
	          //定义一个ServerSocket监听在端口上
	          ServerSocket server = new ServerSocket(port);
	          System.out.println("start");
	          //server尝试接收其他Socket的连接请求,server的accept方法是阻塞式的
	          Socket socket = server.accept();
	          //跟客户端建立好连接之后,我们就可以获取socket的InputStream,并从中读取客户端发过来的信息了。
	          Reader reader = new InputStreamReader(socket.getInputStream());
	          int len;
                  int k=1;
	          StringBuilder sb = new StringBuilder();
	          while (k>0 ) {
       		     char chars[] = new char[60]; 
                     len=reader.read(chars);
                     System.out.println(chars);
                     System.out.println("-----------------");
	          }
	          reader.close();
	          socket.close();
	          server.close();
	       }
	       
	    
}
原网站

版权声明
本文为[帅帅气气的黑猫警长]所创,转载请带上原文链接,感谢
https://blog.csdn.net/Hao_ge_666/article/details/120113580