我需要在AppEngine中创建一个TCP连接(在服务器端)并使其无限期保持活动(或至少约30分钟)。我创建了一个后台线程,打开了java.net.Socket
并尝试读取包含BufferedReader
的行。在大约3秒钟不活动后,我得到以下异常:
java.net.SocketException: Socket operation timed out: The API call remote_socket.Receive() took too long to respond and was cancelled.
我将在下面使用代码I的骨架。任何帮助将不胜感激(包括GAE中套接字限制的变通方法或信息)。谢谢!
ThreadFactory tm = ThreadManager.backgroundThreadFactory();
thread = tm.newThread(new Runnable() {
@Override
public void run() {
Socket socket = null;
try {
socket = new Socket("localhost", 8000);
socket.setSoTimeout(0);
socket.setKeepAlive(true);
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
String in = reader.readLine();
// execution never gets past here
//...
} catch (IOException e) {
e.printStackTrace();
} finally {
// ... <close socket>
}
}
});
thread.start();
如果它是相关的,那么就是用例:我有一个TCP服务器,它曾经在客户端使用嵌入式Applet。我想将Applet重新设计为webapp,但服务器仍能正常工作,所以我宁愿不改变它。我想编写一个简单的servlet来保持TCP连接的活动,并在TCP服务器和GWT客户端之间来回传递消息。
答案 0 :(得分:1)
由于安全原因,套接字在GAE 中有很多限制,但GAE提供了许多现成的服务,这些服务需要使用套接字,例如电子邮件,xmpp等。 / p>
首先,您的应用需要付费应用,表示必须启用结算才能在GAE上使用套接字
您可以拥有look here for how to use sockets in java on GAE
以下是针对套接字限制的Google应用引擎文档的摘录:
App Engine支持套接字,无需您导入任何套接字 特殊的App Engine库或添加任何特殊的App Engine代码。 但是,您需要有一些限制和行为 了解何时使用套接字:
Sockets are available only for paid apps. You cannot create a listen socket; you can only create outbound sockets. java.net.URL is still configured to use the URL Fetch API; there is currently no way around this. Most classes in javax.net.ssl are supported. You can only use TCP or UDP; arbitrary protocols are not allowed. You cannot bind to specific IP addresses or ports. Port 25 (SMTP) is blocked; you can still use authenticated SMTP on the submission port 587. Private, broadcast, multicast, and Google IP ranges (except those whitelisted below), are blocked: Google Public DNS: 8.8.8.8, 8.8.4.4, 2001:4860:4860::8888, 2001:4860:4860::8844 port 53 Gmail SMTPS: smtp.gmail.com port 465 and 587 Gmail POP3S: pop.gmail.com port 995 Gmail IMAPS: imap.gmail.com port 993 Socket descriptors are associated with the App Engine app that created them and are non-transferable (cannot be used by other apps). Sockets may be reclaimed after 2 minutes of inactivity; any socket operation keeps the socket alive for a further 2 minutes. You cannot Select between multiple available sockets because that requires java.nio.SocketChannel which is not currently supported.)