简体   繁体   中英

Send message from client to server

I have develop a chat with an Android client made with android studio and a Server made with Java.

How can i do to send a message from the Client to the server? And from the server broadcast the message to all clients?

Example:

  1. Client#1 send:Hello
  2. Server receive:Hello
  3. Server send the message(Hello) to all other Clients.

Main Server:

package server1;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.*;


public class Server1 {

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

  Socket newsock = null;
    int nreq = 1;
    try
    {
        ServerSocket sock = new ServerSocket (3000);
        for (;;)
        {
            newsock = sock.accept();
            System.out.println("Creating thread ...");
            Thread t = new ThreadHandler(newsock,nreq);
            t.start();

        }
    }
    catch (Exception e)
    {
        System.out.println("IO error " + e);
    }
    System.out.println("End!");

    BufferedReader in=new BufferedReader(new InputStreamReader(newsock.getInputStream()));
    PrintWriter out=new PrintWriter(newsock.getOutputStream(),true);

}

}

ThreadHandler (Server):

package server1;
import java.io.*;
import java.net.*;

class ThreadHandler extends Thread {
Socket newsock;
int n;

ThreadHandler(Socket s, int v) {
    newsock = s;
    n = v;
}


public void run() {
    try {

        PrintWriter outp = new PrintWriter(newsock.getOutputStream(), true);
        BufferedReader inp = new BufferedReader(new InputStreamReader(
                newsock.getInputStream()));

        outp.println("Hello :: enter QUIT to exit \n");
        boolean more_data = true;
        String line;

        while (more_data) {
            line = inp.readLine();
            System.out.println("Message '" + line + "' echoed back to 
 client.");
            if (line == null) {
                System.out.println("line = null");
                more_data = false;
            } else {
                outp.println("From server: " + line + ". \n");
                if (line.trim().equals("QUIT"))
                    more_data = false;
            }
        }
        newsock.close();
        System.out.println("Disconnected from client number: " + n);
    } catch (Exception e) {
        System.out.println("IO error " + e);
    }

}
}

Android MainActivity.java:

package com.example.mirko.chatclient;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;

public class MainActivity extends AppCompatActivity {

    TextView chatzone;
    EditText msg;
    Button btninvio;
    Socket socket;
    PrintWriter out;
    BufferedReader in;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    final int PORTA=3000;
    final String IP = "192.168.1.2";

    try {
        socket=new Socket(IP,PORTA);
    } catch (IOException e) {
        e.printStackTrace();
    }
    //si connette al server

    chatzone= findViewById(R.id.chatzone);
    msg= findViewById(R.id.msg);
    btninvio=findViewById(R.id.btninvia);
    //si dichiara i componenti


    try {
        in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    } catch (IOException e) {
        e.printStackTrace();
    }
    try {
        out= new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
    } catch (IOException e) {
        e.printStackTrace();
    }

}
public void premuto(View v)
{
    String messaggio=msg.getText().toString();
    out.println(messaggio);


}


}

Android xml:

    <?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.mirko.chatclient.MainActivity">

<TextView
    android:id="@+id/chatzone"
    android:layout_width="343dp"
    android:layout_height="309dp"
    android:layout_marginEnd="24dp"
    android:layout_marginStart="24dp"
    android:layout_marginTop="16dp"
    android:text="@string/chatzone"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

<Button
    android:id="@+id/btninvia"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginBottom="32dp"
    android:layout_marginEnd="148dp"
    android:onClick="premuto"
    android:text="@string/invia"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent" />

<EditText
    android:id="@+id/msg"
    android:layout_width="344dp"
    android:layout_height="43dp"
    android:layout_marginBottom="32dp"
    android:layout_marginEnd="24dp"
    android:layout_marginStart="24dp"
    android:layout_marginTop="32dp"
    android:ems="10"
    android:inputType="text"
    android:labelFor="@+id/msg"
    android:text="@string/msg"
    app:layout_constraintBottom_toTopOf="@+id/btninvia"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/chatzone" />

Your server code has a logical problem. You launch a new thread for each client connection. Your ThreadHandler reads and writes to that single client. It has no information on any other possible clients.

Your server must have a "main thread" which handles communication between clients. Your client threads each should have a FIFO queue for outbound messages. The server needs to keep a central FIFO queue of incoming messages and a list of pointers to per-client outbound message queues. Client thread reads a message from its socket then puts it to the central incoming queue. The "main thread" reads messages from that queue and places them into outbounds queues of each client thread. All of this has to be properly synchronized.

So, your client thread reads messages from socket and places them into a common queue, then reads messages from its own outbound queue and writes them to socket. The main thread reads messages from the common incoming queue and writes them to outbound queues of indivual client threads.

In general, the problem you are trying to solve is quite hard. Unless this is a purely learning experience for you and it's OK to fail, you should not build your own. Use something off the shelf, like the one suggested earlier or https://github.com/tinode/chat

Besides, Java is not the best language for such servers-side applications. Most such apps are written in Erlang ( https://github.com/esl/MongooseIM ) and Go.

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