Java套接字(TCP)客户端回调函数

时间:2015-11-08 06:07:02

标签: java android sockets tcp

我正在编写一个简单的Java Socket Client,它能够连接到套接字并将某个请求传递给服务器。几乎就是我想做的事情:

  1. Java Client连接到套接字发送请求到服务器

  2. 服务器处理请求并发回"开始"

  3. Java客户端等待下一次进度更新

  4. 服务器发送"进度10%"

  5. Java客户端接收进度更新并相应处理

  6. 服务器发送进度更新20%......等等如此
  7. 我不想经常检查输入流中是否存在某些内容,而是让客户端在有待处理的情况下立即检索数据并处理它(在后台线程上)。我对使用Java和网络工作一般都很陌生,所以我对实现它并不了解。

    服务器代码(python,在树莓派上运行):

    import SocketServer
    from SocketServer import TCPServer, ThreadingMixIn, StreamRequestHandler
    import sys
    import time
    import socket
    
    # We mix with ThreadingMixIn to allow several simultaneous
    # clients. Otherwise, a slow client may block everyone.
    class ThreadingTCPServer(ThreadingMixIn, TCPServer):
         pass
    
    # StreamRequestHandler provides us with the rfile and wfile attributes
    class RequestHandler(StreamRequestHandler):
    
        def handle(self):
            print str(self.client_address) + 'connected'
            data = "foo"
            while data != "":
                data = self.rfile.readline()
                print data
                try:
                    self.wfile.write("foo\n")
                except socket.error: # Client went away, do not take that data into account
                    data = ""
            print 'Handler Exiting'
            self.request.close()
    
        def finish(self):
            print 'Client Disconnected'
    
    if __name__ == '__main__':
        PORT = 80
    
        ThreadingTCPServer.allow_reuse_address = True
        server = ThreadingTCPServer(("", PORT), RequestHandler)
        try:    
            server.serve_forever()
        except KeyboardInterrupt:
            print "\nServer Terminated"
    

    基本上在原型设计结束时,我将把它实现到Android应用程序中。如果你想知道我打算用它来运行一些家庭自动化和其他一些东西。

    这是我正在使用的当前客户端代码(来自在线示例,我对其进行了一些修改):

    import java.lang.*;
    import java.io.*;
    import java.net.*;
    
    public class ClientTest {
        private Socket socket = null;
        private BufferedReader reader = null;
        private BufferedWriter writer = null;
    
        public ClientTest(InetAddress address, int port) throws IOException {
            socket = new Socket(address, port);
            reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
        }
    
        public void send(String msg) throws IOException {
            writer.write(msg, 0, msg.length());
            writer.flush();
        }
    
        public String recv() throws IOException {
            return reader.readLine();
        }
    
        public static void main(String[] args) {
            try {
                InetAddress host = InetAddress.getByName("192.168.1.15");
                ClientTest client = new ClientTest(host, 80);
                //ClientTest client2 = new ClientTest(host, 9999);
    
                for (int i = 1; i <= 1000; i++) {
                    client.send("bar " + i + "\n");
                    String response = client.recv();
                    System.out.println("" + i + ": " + response);
                    try {
                        Thread.sleep(15);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    //client2.send("Client2\n");
                }
    
    
                client.socket.close();
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                //client2.socket.close();
    
            } catch (IOException e) {
                System.out.println("Caught Exception: " + e.toString());
            }
        }
    }
    

    而不是String response = client.recv();我想在服务器发回请求并在后台处理消息时自动调用此函数。 (我认为这是回调函数的某个方面)

    所有答案都赞赏!

0 个答案:

没有答案