简体   繁体   中英

Creating a TCP Server in Java and send / receive messages

I need help to receive messages for my client and I need a basic TCP Server to receive and send messages to the client.

This is my connection

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

The connection has successfully, but I don't get a log when the client has connected.

This is my server 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);
        }
    }

}

I would start with testing the server; so stop it and then try to 'telnet ' to see if you canNOT get a connection. Then stop it - and check that you do get a connection.

If this works - see if you can enter a line - and if it is logged (ie you got all your end of line characters right; no \\r or \\n fun and games).

Once that work - try your client again. If it still fails; but connects - try having it send 10-20 chars and reading (just) 2 or 3 -- and verify that what you think arrives.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM