我在raywenderlich.com上找到了这个惊人的教程:
http://www.raywenderlich.com/3932/how-to-create-a-socket-based-iphone-app-and-server
它创建了一个Twisted Python服务器,并与app iphone聊天,我会让服务器也与Java聊天,现在我写了一些代码,这是python服务器:
from twisted.internet.protocol import Protocol, Factory
from twisted.internet import reactor
class IphoneChat(Protocol):
def connectionMade(self):
#self.transport.write("""connected""")
self.factory.clients.append(self)
print "clients are ", self.factory.clients
def connectionLost(self, reason):
self.factory.clients.remove(self)
def dataReceived(self, data):
#print "data is ", data
a = data.split(':')
if len(a) > 1:
command = a[0]
content = a[1]
msg = ""
if command == "iam":
self.name = content
msg = self.name + " has joined"
elif command == "msg":
msg = self.name + ": " + content
print msg
for c in self.factory.clients:
c.message(msg)
def message(self, message):
self.transport.write(message + '\n')
factory = Factory()
factory.protocol = IphoneChat
factory.clients = []
reactor.listenTCP(1025, factory)
print "Chat server started"
reactor.run()
然后我创建一个简单的java示例来连接到服务器:
import java.net.*;
import java.io.*;
import java.util.*;
public class MyClassSocket {
private ObjectInputStream sInput; // to read from the socket
private ObjectOutputStream sOutput; // to write on the socket
private Socket socket;
private String server, username;
private int port;
MyClassSocket(String server, int port, String username) {
this.server = server;
this.port = port;
this.username = username;
}
private void display(String msg) {
System.out.println(msg); // println in console mode
}
public boolean start() {
try {
socket = new Socket(server, port);
}
// if it failed not much I can so
catch(Exception ec) {
display("Error connectiong to server:" + ec);
return false;
}
String msg = "Connection accepted " + socket.getInetAddress() + ":" + socket.getPort();
display(msg);
try
{
sInput = new ObjectInputStream(socket.getInputStream()); //<-------- block here
sOutput = new ObjectOutputStream(socket.getOutputStream());
}
catch (IOException eIO) {
display("Exception creating new Input/output Streams: " + eIO);
return false;
}
return true;
}
public static void main(String[] args) {
MyClassSocket client = new MyClassSocket("localhost",1025,"PieroJava");
client.start();
}
}
代码冻结在我在上面的代码中评论的点,我可以在服务器终端中看到有一个新连接,我可以在客户端终端看到我连接但不要在这里:
sInput = new ObjectInputStream(socket.getInputStream());
我该怎么做?
答案 0 :(得分:2)
我建议不要使用ObjectInputStream和ObjectOutputStream。无论如何,让这些与Python服务器很好地交互可能很有挑战性,并且他们无论如何都不会实现非常好的协议。我建议使用更简单的协议,以及更好的跨语言支持,例如AMP。
在任何情况下,new ObjectInputStream
似乎都会被阻塞,直到它可以从连接中读取字节。如果要使其成功,基于Twisted的服务器将需要将Java对象流的开头写入连接。