Python与Java之间Socket通信

来源:互联网 发布:directx9修复软件64位 编辑:程序博客网 时间:2024/06/07 16:03

下面是Python服务器的代码

import sockettry:    sock=socket.socket(socket.AF_INET,socket.SOCK_STREAM);    print("create socket succ!")    sock.bind(('localhost',8001))    print('bind socket succ!')    sock.listen(5)    print('listen succ!')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"welcome client")    conn.close()    print("end of servive")

下面是Java客户端的代码

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 block            e.printStackTrace();        } catch (IOException e) {            e.printStackTrace();        }    }}

一起学习,共同进步!

0 0
原创粉丝点击