Python与Java之间Socket通信

2017-01-01 10:46
  • python socket server
import socket
HOST = '192.168.1.38'
PORT = 50006

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((HOST, PORT))
sock.send("232132132131".encode())

szBuf = sock.recv(1024)
byt = 'recv:' + szBuf.decode('utf-8')
print(byt)

sock.close()
  • python socket client
import socket
HOST = '192.168.1.38'
PORT = 50006

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((HOST, PORT))
sock.send("232132132131".encode())

szBuf = sock.recv(1024)
byt = 'recv:' + szBuf.decode('utf-8')
print(byt)

sock.close()
  • java socket 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 {

        try {
            Socket socket = new Socket("192.168.1.38",50006);

            //获取输出流,向服务器端发送信息
            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();
        }
    }
}
  • 值得注意的是,这里的服务器域名应该写本电脑上的ip,而不是127.0.0.1

来自: http://blog.csdn.net/ChenTianSaber/article/details/52274257?locationNum=4