java socket服务器与安卓多客户端通信

版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/mengxichuan/article/details/83410947

首先我们建立服务端,


public class Main {

    public static void main(String[] args){
        //启动socket服务
        try{
            final ServerSocket server = new ServerSocket(8888);
            System.out.println("服务器已经启动" + server);
            while(true){
                // 服务器接收到链接进来的客户端
                Socket socket = server.accept();
                System.out.println("有客户端链接进来" + socket);
                new Thread(new SocketTast(socket)).start();
            }
        }catch (IOException e){
            e.printStackTrace();
        }

    }

    static class SocketTast implements Runnable{

        private Socket socket;

        public SocketTast(Socket socket){
            this.socket = socket;
        }

        @Override
        public void run(){
            try {

                while (true) {
                    // 处理接收到的数据
                    // 获取输入流,打印客户端信息
                    InputStream inputStream = socket.getInputStream();
                    InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
                    BufferedReader in = new BufferedReader(inputStreamReader);
                    String getinput = in.readLine();
                    if(getinput != null){
                        System.out.println(socket + ":" + getinput);
                        getinput = null;
                    }
                }
            }catch (IOException e){
                e.printStackTrace();
            }
        }
    }
}

然后建立安卓客户端

 

xml

<RelativeLayout
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    tools:layout_editor_absoluteY="25dp">

    <EditText
        android:id="@+id/client_ip"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_marginStart="7dp"
        android:layout_marginTop="370dp"
        android:layout_marginEnd="11dp"
        android:layout_toStartOf="@+id/textView2"
        android:ems="10"
        android:hint="@string/edit_ip"
        android:inputType="textPersonName"
        android:text="@string/ip" />

    <Button
        android:id="@+id/join"
        android:layout_width="126dp"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:layout_marginStart="7dp"
        android:layout_marginTop="506dp"
        android:text="@string/link" />

    <EditText
        android:id="@+id/port"
        android:layout_width="108dp"
        android:layout_height="wrap_content"
        android:layout_above="@+id/edit_msg"
        android:layout_alignParentTop="true"
        android:layout_alignParentEnd="true"
        android:layout_marginTop="371dp"
        android:layout_marginEnd="20dp"
        android:layout_marginBottom="21dp"
        android:ems="10"
        android:hint="@string/edit_port"
        android:inputType="textPersonName"
        android:text="@string/port" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="15dp"
        android:layout_height="41dp"
        android:layout_alignParentTop="true"
        android:layout_marginTop="373dp"
        android:layout_marginEnd="8dp"
        android:layout_toStartOf="@+id/port"
        android:text=":"
        android:textSize="30dp" />

    <TextView
        android:id="@+id/msg"
        android:layout_width="match_parent"
        android:layout_height="344dp"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:layout_marginStart="0dp"
        android:layout_marginTop="8dp" />

    <EditText
        android:id="@+id/edit_msg"
        android:layout_width="374dp"
        android:layout_height="wrap_content"
        android:layout_above="@+id/send"
        android:layout_alignStart="@+id/client_ip"
        android:layout_marginStart="3dp"
        android:layout_marginBottom="22dp"
        android:ems="10"
        android:hint="@string/edit_msg_hint"
        android:inputType="textPersonName" />

    <Button
        android:id="@+id/send"
        android:layout_width="111dp"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_marginStart="14dp"
        android:layout_marginEnd="13dp"
        android:layout_marginBottom="14dp"
        android:layout_toStartOf="@+id/clear"
        android:layout_toEndOf="@+id/join"
        android:text="@string/send_msg" />

    <Button
        android:id="@+id/clear"
        android:layout_width="100dp"
        android:layout_height="wrap_content"
        android:layout_alignTop="@+id/join"
        android:layout_alignEnd="@+id/port"
        android:layout_marginTop="0dp"
        android:layout_marginEnd="-7dp"
        android:text="@string/message_clear" />

</RelativeLayout>

java


public class MainActivity extends AppCompatActivity  {

    private TextView get_msg;   //声明接收文本框
    private EditText ed_msg,c_ip,c_port;   //声明消息,ip,端口编辑框
    private Button send_msg,join,clear_msg;          //声明发送信息按钮、连接按钮与消息清除按钮
    private Socket socket = null;
    private  BufferedReader in;             //声明输入流
    private OutputStream outputStream;      //输出流
    private Thread connectthread,send;              //声明连接线程与发送线程
    private boolean isconnect = false;    //声明连接状态
    private Runnable connection;




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

        get_msg = findViewById(R.id.msg);
        ed_msg = findViewById(R.id.edit_msg);
        send_msg = findViewById(R.id.send);
        c_ip = findViewById(R.id.client_ip);
        c_port = findViewById(R.id.port);
        join = findViewById(R.id.join);
        clear_msg = findViewById(R.id.clear);


        join.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!isconnect) {      //当连接关闭时连接
                    connectthread=new Thread(connection);
                    connectthread.start();       //启动连接线程
                }
                else {  //当再次点击时关闭连接
                    isconnect = false;          //更新连接状态为关闭
                    try {
                        if (socket.isConnected()) {   //检查连接状态
                            //先关闭socket连接,再关闭输入流,输出流
                            socket.close();
                            socket = null;
                            in.close();
                            outputStream.close();
                            Toast.makeText(MainActivity.this, "断开连接!",Toast.LENGTH_SHORT).show();
                            join.setText("连接");
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    //中断连接线程
                    connectthread.interrupt();

                }
            }
        });

        send_msg.setOnClickListener(new View.OnClickListener() {  //发送数据
            @Override
            public void onClick(View v) {
                send = new Thread() {
                    public void run() {
                        try {
                            outputStream.write((ed_msg.getText().toString() + "\n").getBytes("utf-8"));//输出流以utf-8发送数据。
                            outputStream.flush();
                            get_msg.setText(get_msg.getText() + "\rclient: " + ed_msg.getText().toString() + "\n");  //在控件中显示发送的数据。
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                };
                send.start();
            }
        });

        /*
        线程用于连接和接收消息并显示
         */
        connection = new Runnable() {
            @Override
            public void run() {
                try {
                    socket = new Socket(c_ip.getText().toString(), Integer.parseInt(c_port.getText().toString()));  //建立socket,并获取端口,ip
                    in = new BufferedReader(new InputStreamReader(socket.getInputStream()));   //读取输入流
                    outputStream = socket.getOutputStream();   //输出流
                    if (socket.isConnected()) {    //如果连接成功就让按钮显示断开
                        join.setText("断开");             //更新连接按钮显示
                        isconnect = true;          //更新连接状态为连接
                    }
                    String Data = "";
                    while (true) {
                        Data =  in.readLine();  //使用readLine()时服务端发送消息应当以“\n”结尾表示数据发送结束。
                        get_msg.setText(get_msg.getText() + "\rservice: "+Data+"\n");
                    }
                } catch (UnknownHostException e1){
                    e1.printStackTrace();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        };

        clear_msg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                get_msg.setText("");
            }
        });


    }
}

 

 

展开阅读全文

安卓基于socket服务器通信为什么不可以?

05-16

rn这是我做的一个案例不可以实现所以无限接近安卓疯狂讲义的的socket例子.rn请大家看一下指点下子rn服务器 一rnimport java.io.IOException;rnimport java.net.ServerSocket;rnimport java.net.Socket;rnimport java.util.ArrayList;rnimport java.util.List;rnpublic class servers rn static List list = new ArrayList();rn public static void main(String[] args) throws IOException rn System.out.println("======+==== ====");rn // TODO Auto-generated method stubrn ServerSocket ss=new ServerSocket(3369);rn while(true)rn rn System.out.println("+");rn Socket s=ss.accept(); rn new Thread(new runn(s)).start();rn list.add(s);rn rn rn rnrn服务器二:rnpackage dao;rnrnimport java.io.BufferedInputStream;rnimport java.io.BufferedReader;rnimport java.io.IOException;rnimport java.io.InputStream;rnimport java.io.InputStreamReader;rnimport java.net.Socket;rnrnpublic class runn implements Runnablern Socket so=null;rn BufferedReader in=null;rn public runn(Socket so)rn rn this.so=so;rn try rn this. in=new BufferedReader(new InputStreamReader (so.getInputStream(),"utf-8"));rn catch (IOException e) e.printStackTrace(); rn rn @Overridern public void run() rn String s=null;rn try rn while((s=in.readLine())!=null)rn rn for(Socket so:servers.list)rn so.getOutputStream().write(s.getBytes("utf-8"));rn rn catch (IOException e) rn e.printStackTrace();rnrnrn客户端:rnpackage com.s;rnrnimport java.io.BufferedOutputStream;rnimport java.io.BufferedReader;rnimport java.io.BufferedWriter;rnimport java.io.IOException;rnimport java.io.OutputStream;rnimport java.io.OutputStreamWriter;rnimport java.net.Socket;rnimport java.net.SocketTimeoutException;rnimport java.net.UnknownHostException;rnrnimport android.app.Activity;rnimport android.os.Bundle;rnimport android.os.Handler;rnimport android.os.Message;rnimport android.view.View;rnimport android.widget.Button;rnimport android.widget.EditText;rnimport android.widget.TextView;rnrnrnpublic class SockeActivity extends Activity rn EditText input;Button request;TextView t;OutputStream os;rn Socket so; Handler handler;BufferedReader br;BufferedWriter bu;rn Runnable run =new Runnable() rn public void run() rn try rn Message m=new Message();rn String s=null;rn while ((s = br.readLine()) != null) rn ha.sendMessage(m);rn rn catch (IOException e) rn e.printStackTrace();rn rn rn ;rn /** Called when the activity is first created. */rn @Overridern public void onCreate(Bundle savedInstanceState) rn super.onCreate(savedInstanceState);rn setContentView(R.layout.main);rn input=(EditText) findViewById(R.id.editText1);rn request=(Button)findViewById(R.id.button1);rn t=(TextView) findViewById(R.id.textView1);rn try rn this.so=new Socket("192.168.0.105", 3369);rn os=so.getOutputStream();rn catch (UnknownHostException e) rn e.printStackTrace();rn catch (IOException e) rn e.printStackTrace();rn rn rn public void butt(View v) throws IOException rn rn os.write(input.getText().toString().getBytes()); rn os.flush();rn rn rn Handler ha=new Handler()rn rn @Overridern public void handleMessage(Message msg) rn t.append(msg.obj.toString());rn rn ;rn rnrn代码基本都在这里.服务器接收不到客户端的数据,我发现的问题流不关闭都red()一直阻塞了,但是流关闭socket就关闭.我要不关闭socket也能打到接受客户端的信息.指点下.下面是代码的连接,帮我试试谢谢rnhttp://download.csdn.net/detail/yung7086/5388413 论坛

没有更多推荐了,返回首页