简体   繁体   English

套接字客户端停留在“等待来自服务器的消息”。

[英]Socket Client stuck on 'waiting for message from server.'

Backstory: I created a Barcode Scanning app that can connect with my works server. 背景故事:我创建了一个可以与我的工作服务器连接的条形码扫描应用程序。 The Barcode app functions perfectly, however, I have no experience with socket connections to servers. 条形码应用程序功能正常,但是,我没有服务器套接字连接的经验。 So in order to not mess up any code in the Barcode app I copied a tutorial for a socket connection and edited it. 因此,为了不弄乱Barcode应用程序中的任何代码,我复制了一个套接字连接的教程并对其进行了编辑。 Once I can get the test code to complete a connection and send data back and forth, I will implement it into the Barcode app. 一旦获得测试代码以完成连接并来回发送数据,就将其实现到Barcode应用程序中。

The Problem: When I click my button that says "Connect to server" I get this: 问题:当我单击“连接到服务器”按钮时,我得到了:

03-23 11:55:52.174 6438-6459/com.example.vipin.client I/Client: Waiting for message from server...

Pasted below is the code. 下面粘贴的是代码。 I have removed the IP address and Port for security reasons. 出于安全原因,我删除了IP地址和端口。

package com.example.vipin.client;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Client extends AppCompatActivity implements View.OnClickListener {

public static final String TAG = Client.class.getSimpleName();

public static final int SERVERPORT = 0000;

public static final String SERVER_IP = "000.000.0.0";
ClientThread clientThread;
Thread thread;
TextView messageTv;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    messageTv = (TextView) findViewById(R.id.messageTv);
}

public void updateMessage(final String message) {
    runOnUiThread(new Runnable() {
        @Override
        public void run() {
            messageTv.append(message + "\n");
        }
    });
}

@Override
public void onClick(View view) {

    if (view.getId() == R.id.connect_server) {
        messageTv.setText("");
        clientThread = new ClientThread();
        thread = new Thread(clientThread);
        thread.start();
        return;
    }

    if (view.getId() == R.id.send_data) {
        clientThread.sendMessage("Hello from Client");
        Log.i(TAG, "Sending message to server...");
    }
}

class ClientThread implements Runnable {

    private Socket socket;
    private BufferedReader input;

    @Override
    public void run() {

        try {
            InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
            socket = new Socket(serverAddr, SERVERPORT);

            while (!Thread.currentThread().isInterrupted()) {

                Log.i(TAG, "Waiting for message from server...");

                this.input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                String message = input.readLine();
                Log.i(TAG, "Message received from the server : " + message);

                if (null == message || "Disconnect".contentEquals(message)) {
                    Thread.interrupted();
                    message = "Server Disconnected.";
                    updateMessage(getTime() + " | Server : " + message);
                    break;
                }

                updateMessage(getTime() + " | Server : " + message);

            }

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

    }

    void sendMessage(String message) {
        try {
            if (null != socket) {
                PrintWriter out = new PrintWriter(new BufferedWriter(
                        new OutputStreamWriter(socket.getOutputStream())),
                        true);
                out.println(message);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }


    }

}

String getTime() {
    SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
    return sdf.format(new Date());
}

@Override
protected void onDestroy() {
    super.onDestroy();
    if (null != clientThread) {
        clientThread.sendMessage("Disconnect");
        clientThread = null;
    }
}
}

Log for the button click event is here https://pastebin.com/6wbvLj6w 在此处记录按钮单击事件, 网址https://pastebin.com/6wbvLj6w

import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.sql.SQLException;
import javax.imageio.ImageIO;

public class ServerPrintScreen
        extends Thread {

    private ServerSocket serverSocket;

    public ServerPrintScreen(int port)
            throws IOException, SQLException, ClassNotFoundException, Exception {
        serverSocket = new ServerSocket(port);
        serverSocket.setSoTimeout(0);
    }

    public void run() {
        try {
            while (true) {
                Socket clientSocket = serverSocket.accept();
                Throwable localThrowable3 = null;
                try {
                    System.out.println("client connected");
                    clientSocket.setKeepAlive(true);
                    String httpResponse = "HTTP/1.1 200 OK\r\nAccess-Control-Allow-Origin: *\r\nAccept-Ranges: bytes\r\nContent-Disposition: inline;filename=screenShot.jpg\r\nContent-Type: image/jpg\r\n\r\n";
                    BufferedImage originalImage = new Robot().createScreenCapture(new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()));
                    clientSocket.getOutputStream().write(httpResponse.getBytes("UTF-8"));
                    ImageIO.write(originalImage, "jpg", clientSocket.getOutputStream());
                    clientSocket.getOutputStream().flush();
                    clientSocket.getOutputStream().close();
                    clientSocket.close();
                    System.out.println("sent");
                } catch (Throwable localThrowable1) {
                    localThrowable3 = localThrowable1;
                    throw localThrowable1;
                } finally {
                    if (clientSocket != null) {
                        if (localThrowable3 != null) {
                            try {
                                clientSocket.close();
                            } catch (Throwable localThrowable2) {
                                localThrowable3.addSuppressed(localThrowable2);
                            }
                        } else {
                            clientSocket.close();
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace(System.err);
        }
    }

    public static void main(String[] args) throws IOException, SQLException, ClassNotFoundException, Exception {
        Thread t = new ServerPrintScreen(25000);
        t.start();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 客户端向服务器发送消息。 但是服务器没有显示它 - Client sends a message to the server. but server is not displaying it Spring Integration:为什么客户端套接字正在等待服务器的响应? - Spring Integration: Why is client socket waiting for response from server? 等待来自客户端读取消息的套接字服务器 - Socket server that waits for message from client to read Apache Mina Java FTP服务器实现-客户端卡在等待欢迎消息 - Apache Mina Java FTP Server Implementation - Client Stuck Waiting For Welcome Message 我的套接字客户端似乎仅从HTTP服务器收到了第一个响应。 为什么? - My socket client only seems to receive the first response from a HTTP server. Why? Java Socket 服务器 - 客户端; 卡在服务器端 - Java Socket Server - Client; Stuck on Server side 客户端连接但无法向服务器发送消息。[控制台聊天] - Client connects but cant send message to the server.[Console Chat] 通过 Socket Outputstream 从 Swift 客户端向 Java 服务器发送消息 - Send message through Socket Outputstream from Swift Client to Java Server 服务器在等待客户端连接时,如何阻止套接字的接受方法? - how to block the accept method of socket when server is waiting for the connection from client? 套接字客户端-服务器发送到服务器端后卡住 - Socket Client-Server gets stuck after sending to server side
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM