在 Java 中创建 TCP 服务器并发送/接收消息

Creating a TCP Server in Java and send / receive messages

我需要帮助来为我的客户端接收消息,我需要一个基本的 TCP 服务器来接收和向客户端发送消息。

这是我的连接

public class TCPClient {

    private static final String TAG = TCPClient.class.getSimpleName();

    private Socket socket;
    private PrintWriter out;
    private boolean connected;

    public TCPClient() {
        socket = null;
        out = null;
        connected = false;
    }

    public void connect(Context context, String host, int port) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            new ConnectTask(context).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, host, String.valueOf(port));
        } else {
            new ConnectTask(context).execute(host, String.valueOf(port));
        }
    }

    public Boolean isConnected() {
        return connected;
    }

    private class ConnectTask extends AsyncTask<String, Void, Void> {

        private ProgressDialog pDialog;
        private Context context;

        public ConnectTask(Context context) {
            this.context = context;
            pDialog = new ProgressDialog(context);
            pDialog.setTitle(context.getString(R.string.login));
            pDialog.setMessage(context.getString(R.string.connecting) + "...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected void onPostExecute(Void result) {
            if (connected) {
                MainActivity.session.publicname = "BETA-AY";
                MainActivity.session.status = "Hey, ich nutze AYCA!";
                showToast(context, context.getString(R.string.welcome) + " " + MainActivity.session.publicname);
                Intent intent = new Intent(context, ChatsActivity.class);
                context.startActivity(intent);
                ((Activity) context).finish();
            }

            if(pDialog.isShowing()) {
                pDialog.dismiss();
            }
            super.onPostExecute(result);
        }

        @Override
        protected Void doInBackground(String... params) {
            try {
                String host = params[0];
                int port = Integer.parseInt(params[1]);
                socket = new Socket(host, port);
                out = new PrintWriter(socket.getOutputStream(), true);
                connected = true;
            } catch (UnknownHostException e) {
                showToast(context, context.getString(R.string.connectionfail));
                Log.e(TAG, e.getMessage());
            } catch (IOException e) {
                showToast(context, context.getString(R.string.connectionfail));
                Log.e(TAG, e.getMessage());
            }
            return null;
        }

    }

    public void disconnect(Context context) {
        if (connected) {
            try {
                out.close();
                socket.close();
                connected = false;
            } catch (IOException e) {
                Log.e(TAG, e.getMessage());
            }
        }
    }

    public void send(String command) {
        if (connected) {
            out.println(command + ";");
        }
    }

    private void showToast(final Context context, final String message) {
        new Handler(context.getMainLooper()).post(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
            }
        });
    }
}

连接成功,但客户端连接后我没有收到日志。

这是我的服务器class

public class Main {

    static int PORT;

    public static void main(String[] args) throws Exception {

        Logging.Write("Konfigurationen werden geladen...");
        Properties properties = new Properties();
        BufferedInputStream stream = new BufferedInputStream(new FileInputStream("Config.properties"));
        properties.load(stream);
        stream.close();

        PORT = Integer.valueOf(properties.getProperty("PORT")).intValue();

        Logging.Write("Verbindung wird aufgebaut...");

        String clientSentence;
        String capitalizedSentence;
        ServerSocket socket = new ServerSocket(PORT);

        while(true)
        {
            Socket connectionSocket = socket.accept();
            BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
            DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());
            clientSentence = inFromClient.readLine();

            System.out.println("Received: " + clientSentence);

            capitalizedSentence = clientSentence.toUpperCase() + '\n';
            outToClient.writeBytes(capitalizedSentence);
        }
    }

}

我将从测试服务器开始;所以停止它然后尝试 'telnet ' 看看你是否无法连接。然后停止它 - 并检查您是否获得连接。

如果可行 - 查看您是否可以输入一行 - 以及它是否被记录(即您的所有行尾字符都正确;没有 \r 或 \n 的乐趣和游戏)。

一旦成功 - 再次尝试您的客户端。如果还是失败;但连接 - 尝试让它发送 10-20 个字符并读取(仅)2 或 3 个 - 并验证您的想法是否到达。