0

这是我的python代码。

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


蟒蛇服务器

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客户端工作正常

4

0 回答 0