Java 套接字输出流未刷新
我是Android世界的新手,我正在尝试制作一个简单的套接字tcp服务器/客户端聊天应用程序。我正在为服务器使用twisted(python)。以下是源代码:Java 套接字输出流未刷新,java,android,sockets,outputstream,socketserver,Java,Android,Sockets,Outputstream,Socketserver,我是Android世界的新手,我正在尝试制作一个简单的套接字tcp服务器/客户端聊天应用程序。我正在为服务器使用twisted(python)。以下是源代码: from twisted.internet import reactor, protocol, endpoints from twisted.protocols import basic from twisted.internet.address import IPv4Address import threading import dat
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显示“在消息发送之后有消息发送”。
我尝试了不同的方式来发送消息,但同样,服务器不打印任何消息。我还尝试发送\n,但结果相同。服务器不会有问题,因为它正在使用telnet和nc。不要为每条消息创建新的
PrintWriter
。在插座的使用寿命内使用相同的插座。如果对等方正在读取Telnet兼容线路,则发送\r\n
。不行。。。缺少\r\n文件。我尝试过使用\n,但没有使用\r\n谢谢!就是这样工作的。