如何使用我的套接字java PC服务器将我的消息从Android客户端发送到其他Android客户端

时间:2014-10-23 09:03:29

标签: java android sockets

我的代码非常成功地将我的客户端消息发送到服务器..任何人都可以帮忙吗?我是套接字编程的新手。我想建立一个服务器,将我的Android客户端的消息发送到其他Android客户端......这是我的代码

客户端ANDROID:

package com.example.websocketclient;

import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class Chatroom extends Activity {


    public static String msgToServer = null;
    TextView uname;
    EditText in;
    Button snd;
    TextView out;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chatroom);

        uname = (TextView) findViewById(R.id.textViewmynam);
        in = (EditText) findViewById(R.id.editTextInput);
        snd = (Button) findViewById(R.id.buttonSend);
        out = (TextView) findViewById(R.id.textViewOutput);

        Bundle bundle = getIntent().getExtras();
        String urname = bundle.getString("myname");
        uname.setText(urname);

        MyClientTask clientTask = new MyClientTask();
        clientTask.execute();


    }

    public class MyClientTask extends AsyncTask<Void, Void, Void> {
        @Override
        protected Void doInBackground(Void... arg0) {
            connect();
            return null;
            }

    }

    public void connect() {
        Socket sock;
        int[] allports = {1111,1919,2020};
        int portnum;

        for(int i=1;i<allports.length;i++) {
        try {

        portnum = allports[i];
        boolean socketno = Middleware.available(portnum);
        String ad = "192.168.149.1";
        if(socketno = true) {
            sock = new Socket(ad,portnum);
            while(socketno) {
                sendmsg(sock);
        }//while
         //   sock.close();
        }//if

        }catch (UnknownHostException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
    }

    public void sendmsg (final Socket s) {
        snd.setOnClickListener(new View.OnClickListener() {


            @Override
            public void onClick(View arg0) {
                //boolean listening = true;
                String inmsg = ""+in.getText().toString();
                String response = "";

                msgToServer = inmsg;
                //out.append("you:"+msgToServer+"\n");

                 try {
                DataOutputStream outToServer = new DataOutputStream(s.getOutputStream());
                DataInputStream inToServer = new DataInputStream(s.getInputStream());
                if(outToServer != null){
                outToServer.writeBytes(msgToServer+"\n");
                }


                 }
                 catch (Exception e) {

                }

            }
        });

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.chatroom, menu);
        return true;
    }
}

这是我的PC服务器端:

package Server;

import java.net.*;
import java.io.*;
import java.util.Scanner;
import java.net.ServerSocket;
import java.net.Socket;
import java.sql.*;


public class SocketServer extends Thread {

final static int _portNumber = 1919; //Arbitrary port number

      public static void main(String[] args) 
    {
        try {
            new SocketServer().startServer();
        } catch (Exception e) {
            System.out.println("I/O failure: " + e.getMessage());
        }
    }

    public void startServer() throws Exception {
        ServerSocket serverSocket = null;
        boolean listening = true;

        try {
            serverSocket = new ServerSocket(_portNumber);
        } catch (IOException e) {
            System.err.println("Could not listen on port: " + _portNumber);
            System.exit(-1);
        }

        while (listening) {
                        System.out.println("Huwat huwat kang client..!");
            handleClientRequest(serverSocket);
        }

        serverSocket.close();
    }

    private void handleClientRequest(ServerSocket serverSocket) {
        try {
            new Thread(new ConnectionRequestHandler(serverSocket.accept())).start();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * Handles client connection requests. 
     */
    public class ConnectionRequestHandler implements Runnable{
        private Socket _socket;
        private PrintWriter _out;
        private BufferedReader _in;



        public ConnectionRequestHandler(Socket socket) {
            _socket = socket;
        }

        public void run() {
            String info;
            int maxid;

            System.out.println("Client connected to socket: " + _socket.toString()); 
            info = _socket.toString();
            //incrementing the msg_id


            try {
                 BufferedWriter out = new BufferedWriter(new OutputStreamWriter(
                         _socket.getOutputStream()));
                _in = new BufferedReader(new InputStreamReader(_socket.getInputStream()));
                String inputLine;



                Class.forName("com.mysql.jdbc.Driver");
                Connection con = DriverManager.getConnection("jdbc:mysql://localhost/finalclient","root","");
                PreparedStatement st = con.prepareStatement("select *from msgs order by msg_id desc");
                ResultSet r1 = st.executeQuery();
                r1.first(); // or r1.next()
                maxid = r1.getInt("msg_id") + 1;

                while ((inputLine = _in.readLine()) != null) {
                    System.out.println("Message from Client: "+inputLine);
                    out.write(inputLine);
                    try {
                        PreparedStatement st1=con.prepareStatement("insert into msgs  values(?,?,?)");
                        st1.setInt(1,maxid);
                        st1.setString(2,info);
                        st1.setString(3,inputLine);
                        int count = st1.executeUpdate ();

                        System.out.println (count + " rows were inserted to Database");

                    }
                    catch (Exception e) {
                        System.out.println("Failed to Insert from DB"+e);
                    }
                    }
            }
            catch (Exception e) {
                System.out.println("Failed to Select from DB"+e);
            }

                } 
        }
    }       

0 个答案:

没有答案