一、功能描述
使用Python编写socket服务器端代码,使用Java编写socket客户端代码,实现客户端与服务器端的通信,并且客户端接收读取服务器发送的大容量数据。
二、服务器端
编程工具:Pycharm
1.使用pip命令下载socket库。
pip install socket
2.服务器端代码实现,创建server.py文件。服务器可以接收客户端发送的数据并向客户端发送数据。
import socketimport threadingimport sysdef socket_service():try:s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)# 防止socket server重启后端口被占用(socket.error: [Errno 98] Address already in use)s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)s.bind(('127.0.0.1', 6666)) # 绑定服务器IP和端口s.listen(10) # 监听新的客户端连接,设置服务器最大监听数量为10except socket.error as msg:print(msg)sys.exit(1)print('Waiting connection...')while 1:conn, addr = s.accept()#服务器接收的客户端连接t = threading.Thread(target=deal_data1, args=(conn, addr)) t.start()#处理客户端的连接def deal_data1(conn, addr):print('Accept new connection from {0}'.format(addr))data = conn.recv(1024) # 接收客户端发送的数据,byteif data != "":print(data.decode()) # python3 要使用decode进行解码file_object = open('E:\\test1.txt', 'rb')#读取一个文件try:all_the_text = file_object.read()conn.send(all_the_text) # 向客户端发送消息print("长度为: " + str(len(all_the_text)))finally:file_object.close()if __name__ == '__main__':socket_service()
三、客户端
编程工具:IntelliJ IDEA
1.创建maven项目,添加socket依赖。
<!-- 添加Servlet支持 --><dependency><groupId>org.java-websocket</groupId><artifactId>Java-WebSocket</artifactId><version>1.3.8</version></dependency>
2.客户端代码实现,创建MyClient.java文件。向服务器发送数据并接收读取服务器发送的大容量数据。
package webSocket;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import .Socket;public class MyClient {Socket socket = null;OutputStream outputStream = null;InputStream inputStream = null;public MyClient(String host, int port) {try {socket = new Socket(host, port);//host为服务器IP,port为服务器端口outputStream = socket.getOutputStream();inputStream = socket.getInputStream();} catch (IOException e) {e.printStackTrace();}}public void sendRequest(String req) throws IOException {outputStream.write(req.getBytes());//向服务器端发送数据}public String receive() throws IOException {byte[] bytes = new byte[1024*4];int recv = 0;int bytesRead;String re = "";int i=0;do {//接收服务器发送的数据i++;bytesRead = inputStream.read(bytes);recv+=bytesRead;re += new String(bytes,0,bytesRead);} while (bytesRead >= 1024*4);System.out.println("服务器发送的文件大小: "+recv+"读取次数:"+i);return re;}public void close() throws IOException {socket.close();}public static void main(String[] args) {try {String sendMessage = "HELLO SERVER, THIS IS CLIENT";System.out.println("发送给服务器: "+sendMessage);MyClient myClient = new MyClient("127.0.0.1",6666);myClient.sendRequest(sendMessage);String res = myClient.receive();System.out.println("从服务器接收: "+res);} catch (Exception e) {e.printStackTrace();}}}
四、通信验证
首先运行服务器端代码,然后运行客户端代码。
服务器端截图
客户端截图