android不能在带有java的套接字中发送两次printwriter消息也可以不发送java代码而发送python代码

zpgglvta  于 2021-07-05  发布在  Java
关注(0)|答案(1)|浏览(195)

我创建了一个代码,将命令发送到我使用python编写的服务器。代码只工作一次(服务器接收到我第一次发送的内容),但第二次似乎什么也没有发送,因为服务器没有接收到新信息,它一直在等待新信息。我的代码:

StringBuilder Data = new StringBuilder(); // The Data to send

    public void Send(View view) {
        Thread send = new Thread() {

            @Override
            public void run() {
                try {
                    Socket socket = new Socket("20.7.65.2", 6398); // Create connection to the server
                    OutputStream output = socket.getOutputStream(); // Get the key to output to server

                    PrintWriter writer = new PrintWriter(output, true);
                    writer.println(Data.toString()); // Send the data

                    Data.setLength(0); // Delete "Data" contant

                } catch (UnknownHostException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        };

        send.start();
    }

    public void Continue(View view) { 
        Data.append("Hello from client"); // Append to "Data"

        Send(null); // Run the send functionn (again)

    }

    }

我的python服务器:

import socket, time

soc = socket.socket()
soc.bind((socket.gethostname(), 6398))

soc.listen(5)
(client, (ipNum, portNum)) = soc.accept()

print("Client connected")

while True:
    message = client.recv(1024).decode()

    if(message != ""):
        print(message)
    time.sleep(0.1)

简而言之,我尝试运行run函数两次。第一次它发送到服务器并接收信息,第二次服务器仍在等待信息,没有再次接收到我发送的信息。可能是因为他无法接收所有客户发给他的所有信息
也可以不给我发送java代码,而是发送一个python代码来工作并接收来自所有客户机的所有消息

oprakyz7

oprakyz71#

在您的代码中,服务器只接受一次cnconnection,然后从同一个客户机接收cnconnection。但是根据你的问题,我认为你的服务器应该能够监听多个客户端,因此,你可以在服务器上使用多线程。我没有给客户机线程化,而是使用了一个按钮,单击该按钮可以连接服务器。我也不能理解客户端线程的需要。如果你认为答案需要修改,你可以发表评论。
这是python服务器

import socket, time
import threading

soc = socket.socket()

# print(socket.)

soc.bind(("192.168.1.5", 6398))

soc.listen(5)

def info(client):
    message = client.recv(1024).decode()
    if(message != ""):
        print(message)
    return

while True:
    (client, (ipNum, portNum)) = soc.accept()
    print("Client connected")
    threading.Thread(target=info,args=(client,)).start()

主活动.java

package com.example.myapplication;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

public class MainActivity extends AppCompatActivity {
    StringBuilder Data = new StringBuilder(); // The Data to send
    private Button btn;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btn= findViewById(R.id.connectBtn);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Continue();
            }
        });
    }

    public void Send() {
        Thread send = new Thread() {

            @Override
            public void run() {
                try {
                    Socket socket = new Socket("192.168.1.5", 6398); // Create connection to the server
                    OutputStream output = socket.getOutputStream(); // Get the key to output to server

                    PrintWriter writer = new PrintWriter(output, true);
                    writer.println(Data.toString()); // Send the data

                    Data.setLength(0); // Delete "Data" contant

                } catch (UnknownHostException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        };

        send.start();
    }

    public void Continue() {
            Data.append("Hello from client"); // Append to "Data"

            Send(); // Run the send functionn (again)
    }

}

别忘了加上 <uses-permission android:name="android.permission.INTERNET"/> 在androidmanifest.xml中。
活动\u main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/connectBtn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

相关问题