Java 使用套接字将多个数据发送到服务器

Java 使用套接字将多个数据发送到服务器,java,android,sockets,Java,Android,Sockets,我只是想做一个像whatssap这样的聊天应用。我需要发送一个独特的数据,这将是分开的客户端彼此例如用户名或电话号码从客户端到服务器。并使用此数据从服务器到客户端发送到正确的客户端。但我真的很害怕。如果不将用户名与消息分开,我无法将其发送到服务器端。有人能告诉我一种从客户端到服务器发送多个数据的简单方法吗?就像在socket.io中一样,您可以很容易地通过标记来完成。但在java中,据我所知,您必须从一个套接字读取所有数据 客户端 import java.net.UnknownHostExcep

我只是想做一个像whatssap这样的聊天应用。我需要发送一个独特的数据,这将是分开的客户端彼此例如用户名或电话号码从客户端到服务器。并使用此数据从服务器到客户端发送到正确的客户端。但我真的很害怕。如果不将用户名与消息分开,我无法将其发送到服务器端。有人能告诉我一种从客户端到服务器发送多个数据的简单方法吗?就像在socket.io中一样,您可以很容易地通过标记来完成。但在java中,据我所知,您必须从一个套接字读取所有数据

客户端

import java.net.UnknownHostException;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;


public class AndyChatActivity extends Activity {

    private Handler handler = new Handler();
    public ListView msgView;
    public ArrayAdapter<String> msgList;
//  public ArrayAdapter<String> msgList=new ArrayAdapter<String>(this,
//          android.R.layout.simple_list_item_1);;
    String name;
    EditText txtEdit;
    EditText txtEdit1;
    String text;
    String text1;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        name =  getIntent().getStringExtra("name");


         msgView = (ListView) findViewById(R.id.listView);

        msgList = new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1);
        msgView.setAdapter(msgList);

//      msgView.smoothScrollToPosition(msgList.getCount() - 1);

        Button btnSend = (Button) findViewById(R.id.btn_Send);

        receiveMsg();
        btnSend.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                txtEdit = (EditText) findViewById(R.id.txt_inputText);
                txtEdit1 = (EditText) findViewById(R.id.txt_inputText1);
                text = txtEdit.getText().toString();
                text1 = txtEdit1.getText().toString();

                //msgList.add(txtEdit.getText().toString());
                sendMessageToServer(text1.toString());
                sendMessageToServer(text.toString());
                sendMessageToServer(name.toString());


                msgView.smoothScrollToPosition(msgList.getCount() - 1);

            }           
        });

//      receiveMsg();
        //----------------------------
        //server msg receieve
        //-----------------------



        //End Receive msg from server//
    }
public void sendMessageToServer(String str,String name) {

        final String str1=str;
        final String name1="Name:"+name;
        new Thread(new Runnable() {

            @Override
            public void run() {
                // TODO Auto-generated method stub
                //String host = "opuntia.cs.utep.edu";
                String host="10.0.2.2";
                PrintWriter out;
                PrintWriter out1;
                try {
                    Socket socket = new Socket(host, 8000);
                    out = new PrintWriter(socket.getOutputStream());
                    out1 = new PrintWriter(socket.getOutputStream());

                    out1.println(name1);
                    out.println(str1);
                    Log.d("", "hello");
                    out.flush();
                } catch (UnknownHostException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    Log.d("", "hello222");
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    Log.d("", "hello4333");
                }

            }
        }).start();
            }



    public void receiveMsg()
    {
        new Thread(new Runnable()
        {
            @Override
            public void run() {
                // TODO Auto-generated method stub

                //final  String host="opuntia.cs.utep.edu";
                final String host="10.0.2.2";
                //final String host="localhost";
                Socket socket = null ;
                BufferedReader in = null;
                try {
                    socket = new Socket(host,8000);
                } catch (UnknownHostException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

                try {
                    in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

                while(true)
                {

                    String msg = null;
                    try {

                        msg = in.readLine();
                        Log.d("","MSGGG:  "+ msg);

                        //msgList.add(msg);
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    if(msg == null)
                    {
                        break;
                    }
                    else
                    {
                        displayMsg(msg);
                    }
                }

            }
        }).start();


    }

    public void displayMsg(String msg)
    { 
        final String mssg=msg;
        handler.post(new Runnable() {

            @Override
            public void run() {
                // TODO Auto-generated method stub
                msgList.add(mssg);
                msgView.setAdapter(msgList);
                msgView.smoothScrollToPosition(msgList.getCount() - 1);
                Log.d("","hi");
            }
        });

    }

}
服务器端

package edu.UTEP.android;
// $Id: ChatServer.java,v 1.3 2012/02/19 06:12:34 cheon Exp $

import java.io.*;
import java.net.*; 
import java.util.*;


public class ChatServer {

    private static final String USAGE = "Usage: java ChatServer";

    /** Default port number on which this server to be run. */
    private static final int PORT_NUMBER = 8000;

    /** List of print writers associated with current clients,
     * one for each. */
    private List<PrintWriter> clients;

    /** Creates a new server. */
    public ChatServer() {
        clients = new LinkedList<PrintWriter>();
    }

    /** Starts the server. */
    public void start() {
        System.out.println("AndyChat server started on port "
                           + PORT_NUMBER + "!"); 
        try {
            ServerSocket s = new ServerSocket(PORT_NUMBER); 
            for (;;) {
                Socket incoming = s.accept(); 
                new ClientHandler(incoming).start(); 
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("AndyChat server stopped."); 
    }

    /** Adds a new client identified by the given print writer. */
    private void addClient(PrintWriter out) {
        synchronized(clients) {
            clients.add(out);
        }
    }

    /** Adds the client with given print writer. */
    private void removeClient(PrintWriter out) {
        synchronized(clients) {
            clients.remove(out);
        }
    }

    /** Broadcasts the given text to all clients. */
    private void broadcast(String msg) {
        for (PrintWriter out: clients) {
            out.println(msg);
            out.flush();
        }
    }

    public static void main(String[] args) {
        if (args.length > 0) {
            System.out.println(USAGE);
            System.exit(-1);
        }
        new ChatServer().start();
    }

    /** A thread to serve a client. This class receive messages from a
     * client and broadcasts them to all clients including the message
     * sender. */
    private class ClientHandler extends Thread {

        /** Socket to read client messages. */
        private Socket incoming; 

        /** Creates a hander to serve the client on the given socket. */
        public ClientHandler(Socket incoming) {
            this.incoming = incoming;
        }

        /** Starts receiving and broadcasting messages. */
        public void run() {
            PrintWriter out = null;
            try {
                out = new PrintWriter(
                        new OutputStreamWriter(incoming.getOutputStream()));

                // inform the server of this new client
                ChatServer.this.addClient(out);

                out.print("Welcome to AndyChat! ");
                out.println("Enter BYE to exit."); 
                out.flush();

                BufferedReader in 
                    = new BufferedReader(
                        new InputStreamReader(incoming.getInputStream())); 
                for (;;) {
                    String msg = in.readLine(); 
                    if (msg == null) {
                        break; 
                    } else {
                        if (msg.trim().equals("BYE")) 
                            break; 
                        System.out.println("Received: " + msg);
                        // broadcast the receive message
                        ChatServer.this.broadcast(msg);
                    }
                }
                incoming.close(); 
                ChatServer.this.removeClient(out);
            } catch (Exception e) {
                if (out != null) {
                    ChatServer.this.removeClient(out);
                }
                e.printStackTrace(); 
            }
        }
    }
}

您需要为应用程序创建e协议。比如说,使用当前用户昵称存储当前连接的套接字,如前面提到的fredcrs,将消息以可解析的格式发送到服务器,例如,从消息到消息,然后拆分元素并将其定向到应用程序中。另一种更简单的方法是使用JSON或XML等现有格式……您能提供一个关于协议的示例吗?我已经搜索了很多次,但在@fredcrs中找不到任何内容