我是Android界的新手,我正在尝试制作一个简单的socket tcp服务器/客户端聊天应用程序。我正在使用twisted(python)作为服务器。这是源代码:
from twisted.internet import reactor, protocol, endpoints
from twisted.protocols import basic
from twisted.internet.address import IPv4Address
import threading
import datetime, time
# Broadcast to all clients
def broadcast(clients, text):
for c in clients:
try:
c.sendLine(text)
except Exception:
print '[!] Cannot send message to' + c.getIp()
# SocketServer class
class PubProtocol(basic.LineReceiver):
def __init__(self, factory):
self.factory = factory
def connectionMade(self):
ip = self.transport.getHost().host
print "[+] Client {} connected".format(ip)
self.factory.clients.add(self)
def connectionLost(self, reason):
self.factory.clients.remove(self)
print '[+] Client disconnected'
def lineReceived(self, line):
# Get IP
ip = self.transport.getHost().host
# Get current time
time = datetime.datetime.now().strftime("%H:%M:%S")
# Build message to send
text = "[{}] {}: {}".format(time, ip, line)
# Print text to server
print text
# Broadcast to all clients
broadcast(self.factory.clients, text)
class PubFactory(protocol.Factory):
def __init__(self):
self.clients = set()
def buildProtocol(self, addr):
return PubProtocol(self)
print '[+] Server started'
endpoints.serverFromString(reactor, "tcp:1025").listen(PubFactory())
reactor.run()
我已经使用telnet对其进行了测试,我在telnet终端中编写的所有内容都显示在我的服务器控制台中,并且还会发送回客户端。
一切顺利,直到我开始编写客户端在java中发送消息部分。这是我的sendMessage函数:
private void sendMessage(String text) throws IOException {
Log.d("ME", "In message function");
if (!goodToGo) {
Log.d("ME", "In: goodToGo = false");
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Not connected to server.");
builder.setTitle("Error");
builder.show();
return;
}
OutputStream outputStream = socket.getOutputStream();
PrintWriter out = new PrintWriter(outputStream);
out.print(text);
out.print("");
out.flush();
Log.d("ME", String.format("after message %s sent", text));
}
我只有在连接到服务器后才会调用此函数(100%确定!)
问题是,在我发送消息之后,我的服务器控制台中什么也没有得到,即使logcat向我显示了"之后发送消息some_message"。 我尝试了不同的方式发送邮件,但同样,服务器不会打印任何邮件。我也尝试发送 \ n ,但结果相同。服务器不是问题,因为它使用telnet和nc。