使用Java创建TCP服务器并发送/接收消息

时间:2015-03-22 17:00:41

标签: java tcp

我需要帮助来接收客户端的消息,我需要一个基本的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();
            }
        });
    }
}

连接已成功,但在客户端连接时我没有得到日志。

这是我的服务器类

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);
        }
    }

}

1 个答案:

答案 0 :(得分:0)

我将从测试服务器开始;所以停下来然后尝试telnet&#39;看看你是否无法建立连接。然后停止它 - 并检查你是否有连接。

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

完成这项工作后 - 再次尝试您的客户。如果它仍然失败;但连接 - 尝试发送10-20个字符并阅读(只)2或3 - 并验证您的想法到达。