1. java与python之间的数据传递
PrintWriter:
OutputStream os=socket.getOutputStream();//字节输出流
PrintWriter pw=new PrintWriter(os);//将输出流包装为打印流
pw.write("我是Java服务器");
pw.flush();
socket.shutdownOutput();//关闭输出流
write是写入一个字符串.PrintWriter是把对象的格式化表示打印到文本输出流。
ObjectOutputStream:An ObjectOutputStream writes primitive data types and graphs of Java objects to an OutputStream。读取的时候用ObjectInputStream。
writeObject是把一个对象写入输出流。读取的时候必须转换成同一类型的数据。
OutputStream flush():确保还在缓冲区的数据都发到目的地去。
socket.shutdownOutput():关闭输出流。不再能发送数据的。
socket.getOutputStream():返回一个输出流用于给定的socket.大致作用是在这个流里面发送数据给server.
socket.getInputStream();这个好理解了,大概是得到一个输入流,然后可以从这个socket里面接受数据。
BufferedReader:是一个从字符输入流中简化文本读取的类,为了高效读取文本数据,它把字符存到缓冲区里面。什么时候用?当你要读入文本数据的时候,不管是socket还是文件。
它减少了I/O操作的次数,它读取大量的字符然后存到内部缓冲区,reader就直接在buffer里面读取而不是直接依赖输入源。
它的输入参数要是一个reader,比如
BufferedReader reader =new BufferedReader(new FileReader("src/main/resources/input.txt"));//another not related example// 16384 mean:buffer size.//This will set the buffer size to 16384 bytes (16 KB).BufferedReader reader =new BufferedReader(new FileReader("src/main/resources/input.txt")), 16384);
它的功能就是buffering,如果你不需要这个功能,可以直接
FileReader reader =new FileReader("src/main/resources/input.txt");
用filereader直接读取。
java.io.BufferedReader.readline():读取文本的一行。一行结束的标志是换行' ‘java基础学习python,回车' ',或者紧跟在换行后面的回车' '.输入完了即到了null,不读入null.
完整的例子:
//客户端import java.io.BufferedReader;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.io.OutputStream;import java.io.PrintWriter;import java.net.Socket;import java.net.UnknownHostException;public class SocketClient {public static void main(String args[])throws Exception {try {Socket socket = new Socket("localhost",8001);//获取输出流,向服务器端发送信息OutputStream os=socket.getOutputStream();//字节输出流PrintWriter pw=new PrintWriter(os);//将输出流包装为打印流pw.write("我是Java服务器");pw.flush();socket.shutdownOutput();//关闭输出流InputStream is=socket.getInputStream();BufferedReader in = new BufferedReader(new InputStreamReader(is));String info=null;while((info=in.readLine())!=null){System.out.println("我是客户端,Python服务器说:"+info);}is.close();in.close();socket.close();} catch (UnknownHostException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {e.printStackTrace();}}}
import sockettry:sock=socket.socket(socket.AF_INET,socket.SOCK_STREAM)sock.bind(('localhost',8001))sock.listen(5)except:print("init socket error!")while True:print("listen for client...")conn,addr=sock.accept()print("get client")print(addr)# conn.settimeout(30)szBuf=conn.recv(1024)print("recv:"+str(szBuf,'gbk'))if "0"==szBuf:conn.send(b"exit")else:conn.send(b"this is server's message. ")conn.close()print("end of servive")
client改成循环.
import java.io.BufferedReader;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.io.OutputStream;import java.io.PrintWriter;import java.net.Socket;import java.net.UnknownHostException;public class SocketClient {public static void main(String args[])throws Exception {while(true){try {Socket socket = new Socket("localhost",8001);//获取输出流,向服务器端发送信息OutputStream os=socket.getOutputStream();//字节输出流PrintWriter pw=new PrintWriter(os);//将输出流包装为打印流pw.write("我是Java服务器");pw.flush();socket.shutdownOutput();//关闭输出流InputStream is=socket.getInputStream();BufferedReader in = new BufferedReader(new InputStreamReader(is));String info=null;while((info=in.readLine())!=null){System.out.println("我是客户端,Python服务器说:"+info);}is.close();in.close();socket.close();} catch (UnknownHostException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {e.printStackTrace();}}}}
分析:
server:socket.accpet()会监听是否有客户端连接.有连接之后,szBuf=conn.recv(1024).等待数据发送过来.
client:Socket socket = new Socket("localhost",8001)连接之后,server accpet()部分结束,走到conn.revv部分.
pw.write("我是Java服务器");数据发送,conn.recv结束,client:info=in.readLine()等待.
这么看,连接和I/O操作的时候会停下来监听。
socket close之后,要重新连接。
2.Python之间的数据传递
传输字典数据例子
//clientimport socketimport jsonsendData={'2016-07-21':{'value':1000,'titles':[u'标题1',u'标题2',u'标题3']},'2016-07-22':{'value':2000,'titles':[u'标题4',u'标题5',u'标题6']},'2016-07-23':{'value':3000,'titles':[u'标题7',u'标题8',u'标题9']}}HOST='localhost'PORT=10001s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)s.connect((HOST,PORT))s.sendall(bytes(json.dumps(sendData).encode('utf-8')))s.close()#关闭连接
发送数据的时候,要把数据序列化才能传输。json.dumps(sendData)把字典数据序列化Python之数据序列化(json、pickle、shelve) - 云游道士 - 博客园.encode()部分是序列化的一部分,如果不加这个会报错:string argument without an encoding.
如果要将一个系统内的数据通过网络传输给其它系统或客户端,我们通常都需要先把这些数据转化为字符串或字节串,而且需要规定一种统一的数据格式才能让数据接收端正确解析并理解这些数据的含义。
大概是因为要序列化成字符串,字符串的格式需要设定,设定成utf-8是一种选择。
//serverimport socket#socket模块# import commands #执行系统命令模块HOST='localhost'PORT=10001s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)#定义socket类型,网络通信,TCPs.bind((HOST,PORT))#套接字绑定的IP与端口s.listen(1)#开始TCP监听while True:conn,addr=s.accept()#接受TCP连接,并返回新的套接字与IP地址print('Connected by',addr)#输出客户端的IP地址data=conn.recv(10024)#把接收的数据实例化if len(data.strip()) ==0:conn.sendall('Done.')else:recData =eval(data) # 使用eval()函数恢复序列化后的字典for key,value in recData.items():print(key,value['value'])for item in value['titles']:print(item)print()conn.sendall(b'Successful')#否则就把结果发给对端(即客户端)conn.close()
recData =eval(data) # 使用eval()函数恢复序列化后的字典recdata就是一个字典了。
版权声明:
本文来源网络,所有图片文章版权属于原作者,如有侵权,联系删除。
本文网址:https://www.bianchenghao6.com/h6javajc/2167.html