我正在嘗試使用 python 中的服務器撰寫應用程式。一切都完美連接,字串是從 android 發送的,但無法從服務器獲取字串。嘗試獲取字串時,流被簡單地阻塞,如果設定了超時,則簡單地呼叫例外“超時”,這是合乎邏輯的。我已經嘗試了所有方法,我將立即向您展示我目前遇到的所有發送和接收代碼(同時使用 BufferedReader().ready(),一切正常)
蟒蛇服務器
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind(server_address)
server_socket.listen(1)
print ('Waiting for a client connection...')
connection, client_address = server_socket.accept()
print ('Connected to:', client_address)
# listen for data for forever
while True:
data = connection.recv(data_size)
print ('Received', data.decode('utf-8')) # print as raw bytes
sizeOfMainMsg = int(data.decode('utf-8'))
data = connection.recv(sizeOfMainMsg)
print ('Received', data.decode('utf-8')) # print as raw bytes
toSendTry = "Sendet "
connection.send(bytes(toSendTry,'UTF-8'))
Kotlin 客戶端
clientSocket = Socket(SERVER_ADDRESS, SERVER_PORT)
clientSocketOut = clientSocket!!.getOutputStream()
clientSocketIn = clientSocket!!.getInputStream()
if (clientSocket != null) {
while (clientSocketOut != null && clientSocketIn != null && clientSocket!!.isConnected()) {
var tmp = clientSocketIn!!.bufferedReader(Charsets.UTF_8)
if(tmp.ready()){
recived.add(tmp.readLine()) #This is where the problems occur
}
if (toSend.size > 0){
for (nowMsg in toSend){
clientSocketOut!!.write(nowMsg.toByteArray(Charsets.UTF_8).size.toString().toByteArray(Charsets.UTF_8))
clientSocketOut!!.flush()
clientSocketOut!!.write(nowMsg.toByteArray(Charsets.UTF_8))
clientSocketOut!!.flush()
}
toSend.clear()
}
}
(不用說,kotlin 客戶端代碼是用 AsyncTask 寫的)
uj5u.com熱心網友回復:
您的客戶嘗試讀取一行。
現在為了成功,服務器應該發送一條線。
一行不僅僅是一個字串。
看看 newline character。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/520779.html
上一篇:有沒有辦法減少冗余?
下一篇:與UDP中的不同埠通信
