socket.recv无法使用非阻塞

时间:2013-10-14 17:16:41

标签: java python sockets

这是我的python代码。

每当我尝试发送一个字符串时,它都不会收到,并在10秒后超时。


python服务器

import socket               # Import socket module
import sys 
import select

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)        # Create a socket object
host = "127.0.0.1" # Get local machine name
port = 50001               # Reserve a port for your service.
s.bind((host, port))        # Bind to the port

a = []
b = []

s.listen(1)                 # Now wait for client connection.
c, addr = s.accept()     # Establish connection with client.

s.setblocking(0)

ready = select.select([s], [s], [s], 10)
while True:
   if ready[0]:
      data = s.recv(4096)
      print data
      print "reached"
   print 'Got connection from', addr
   c.send('Thank you for connecting \r\n') #all strings have to end with /r/n!!!
   print "sent"
   break;
c.close()                # Close the connection

我的Java客户端


import java.net.*;
import java.io.*;

public class MTExample

{

    public MTExample()

    {
        String sentence;   
        String modifiedSentence = "undefined";

        try
        {
            //ceating the socket to connect to server running on same machine binded on port no 3000
            Socket client = new Socket("127.0.0.1", 50001);
            System.out.println("Client connected ");

            //getting the o/p stream of that connection
            PrintStream out = new PrintStream(client.getOutputStream());

            //sending the message to server
            System.out.print("Hello from client\n");
            System.out.flush();

            //reading the response using input stream
            //BufferedReader in= new BufferedReader(new InputStreamReader(client.getInputStream()));
            BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

            //System.out.println(in.readLine());
            //closing the streams
            sentence = in.readLine();   


            sentence = "haha";
            DataOutputStream outToServer = new DataOutputStream(client.getOutputStream());   

            outToServer.writeBytes(sentence + "\n");   


            BufferedReader inFromServer = new BufferedReader(new InputStreamReader(client.getInputStream()));

             modifiedSentence = inFromServer.readLine();  

             System.out.println(modifiedSentence);

             System.out.println("FROM SERVER: " + modifiedSentence);   
             client.close();
             in.close();
             out.close();           
        }
        catch(Exception err)
        {
            System.err.println("hi* err"+err);
        }               
    }

    public static void main(String a[])
    {
         new MTExample();
    }

}

Python中的非阻塞方法有问题吗?在我将python上的阻塞段更改为在recv套接字上无阻塞之前,Java客户端工作正常

0 个答案:

没有答案