gpt4 book ai didi

java - 服务器发送消息给客户端

转载 作者:行者123 更新时间:2023-12-01 13:31:07 24 4
gpt4 key购买 nike

我正在开发一个使用 TCP/IP 的 Android 应用程序。我可以轻松地将消息从服​​务器发送到客户端,但我可以弄清楚如何从服务器向客户端发送消息。我环顾四周,找不到答案。它只是某种输出编写器吗?

Public class MainActivity extends Activity {

private ServerSocket serverSocket;
Handler updateConversationHandler;
Thread serverThread = null;
private TextView text;
public static final int SERVERPORT = 6000;

@Override
public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);
setContentView(R.layout.main);
text = (TextView) findViewById(R.id.text2);
updateConversationHandler = new Handler();
this.serverThread = new Thread(new ServerThread());
this.serverThread.start();
}

@Override
protected void onStop() {
super.onStop();
try {
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}

class ServerThread implements Runnable {

public void run() {
Socket socket = null;
try {
serverSocket = new ServerSocket(SERVERPORT);
} catch (IOException e) {
e.printStackTrace();
}

while (!Thread.currentThread().isInterrupted()) {
try {
socket = serverSocket.accept();
CommunicationThread commThread = new CommunicationThread(socket);
new Thread(commThread).start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

class CommunicationThread implements Runnable {
private Socket clientSocket;
private BufferedReader input;
public CommunicationThread(Socket clientSocket) {
this.clientSocket = clientSocket;
try {
this.input = new BufferedReader(new InputStreamReader(this.clientSocket.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
}
}

public void run() {
while (!Thread.currentThread().isInterrupted()) {
try {
String read = input.readLine();
updateConversationHandler.post(new updateUIThread(read));
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

class updateUIThread implements Runnable {
private String msg;
public updateUIThread(String str) {
this.msg = str;
}

@Override
public void run() {
text.setText("");
if (msg != null){
text.setText(text.getText().toString()+"binary message sent: "+ msg + "\n");
String[] list_bin = new String[list_command.length];

for(int i=0 ; i<list_command.length; i++){
list_bin[i] = Integer.toBinaryString(i);
if ( list_bin[i] == null ? msg == null : list_bin[i].equals(msg)){
msg = list_command[i];
}
}

text.setText(text.getText().toString()+"Found input : "+ msg + "\n");
}
}
}

如何让服务器向客户端发送消息?

最佳答案

最简单的方法是在 clientSocket.getOutputStream 上使用 OutputStreamWriter,并从单独的线程写入。

关于java - 服务器发送消息给客户端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21566651/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com