通过Socket实现最基础的群聊天功能

  • 服务端 Eclipse
package server;

import java.io.IOException;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;

/*Eclipse*/
public class ServerSocekt {

    public static ArrayList<Socket> socketList = new ArrayList<Socket>();

    public static void main(String[] args) throws IOException{
        ServerSocket ss = new ServerSocket(30000); 
        while(true){
            Socket s = ss.accept();
            socketList.add(s);
            new Thread(new SocketRun(s)).start();
        }
    }

}
package server;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;


/*Eclipse*/
public class SocketRun implements Runnable{

    Socket s = null;
    BufferedReader br = null;

    public SocketRun(Socket s) throws IOException{
        this.s = s;
        br = new BufferedReader(new InputStreamReader(s.getInputStream()));
    }

    @Override
    public void run() {
            while(true){
                String content = readFromClient();
                if(content!=null){
                    for(Socket s : ServerSocekt.socketList){
                        PrintStream ps;
                        try {
                            ps = new PrintStream(s.getOutputStream());
                            ps.println(content);
                        } catch (IOException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                }
            }
    }

    private String readFromClient(){

        try {
            return br.readLine();
        } catch (IOException e) {
            e.printStackTrace();

        }
        return null;
    }
}
  • 客户端 Android Studio
package com.mystudy.kibi.sockettest;

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

import java.io.IOException;
import java.io.PrintStream;
import java.net.Socket;

//Android Studio
public class MainActivity extends AppCompatActivity {

    private EditText editText;
    private static TextView textView;
    private Socket socket;
    private static StringBuffer stringBuffer = new StringBuffer("");
    private Boolean isTrue = false;

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

        editText = (EditText) findViewById(R.id.tv);
        textView = (TextView) findViewById(R.id.text);

        new Thread(){
            @Override
            public void run() {
                try {
                    socket = new Socket("192.168.0.101",30000);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }.start();

        new Thread(){
        @Override
        public void run() {
                try {
                    sleep(2000);
                    new Thread(new ClientRun(socket)).start();
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }.start();



        findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                new Thread(){
                    @Override
                    public void run() {
                        try {
                            String str = editText.getText().toString();
                            connect(str);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }.start();
            }
        });

    }

    private void connect(String str) throws IOException {
        PrintStream printStream = new PrintStream(socket.getOutputStream());
        printStream.println(str+"\r\n");
    }

    public static Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            Bundle bundle = msg.getData();
            String str = bundle.get("msg").toString();
            stringBuffer.append(str+"\n");
            textView.setText(stringBuffer.toString()+"");
        }
    };

}
package com.mystudy.kibi.sockettest;

import android.os.Bundle;
import android.os.Message;

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

/**
 * Created by Nicole on 16/9/8.
 */
public class ClientRun implements Runnable {

    private Socket socket;
    private BufferedReader bufferedReader = null;

    public ClientRun(Socket socket) throws IOException {
        this.socket = socket;
        bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    }

    @Override
    public void run() {
            while (true){
                String content = null;
                try {
                    content = bufferedReader.readLine();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                if(content!=null){
                    Message message = new Message();
                    Bundle bundle = new Bundle();
                    bundle.putString("msg",content);
                    message.setData(bundle);
                    MainActivity.handler.sendMessage(message);
                }

            }
    }
}
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.mystudy.kibi.sockettest.MainActivity">

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="50dp"
        android:text="Hello World!" />

    <EditText
        android:id="@+id/tv"
        android:layout_marginTop="60dp"
        android:layout_width="match_parent"
        android:layout_height="50dp" />

    <TextView
        android:id="@+id/text"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginTop="120dp">

    </TextView>


</RelativeLayout>
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值