博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
socket简易聊天室
阅读量:5781 次
发布时间:2019-06-18

本文共 8611 字,大约阅读时间需要 28 分钟。

hot3.png

服务器端
import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.io.OutputStreamWriter;import java.io.PrintWriter;import java.net.ServerSocket;import java.net.Socket;import java.util.ArrayList;import java.util.List;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;/** * @version 2012-7-26 下午04:04:18 **/public class server {    // 服务器端口    private static final int SERVERPORT = 54321;    // 客户端连接    private static List
mClientList = new ArrayList
(); // 线程池 private ExecutorService mExecutorService; // serverSocket对象 private ServerSocket mServerSocket; public static void main(String[] args) { new server(); } public server() { try { // 设置服务器端口 mServerSocket = new ServerSocket(SERVERPORT); // 创建一个线程池 mExecutorService = Executors.newCachedThreadPool(); System.out.println("start..."); // 用来临时保存客户端连接的Socket对象 Socket client = null; while(true) { // 接受客户度连接并添加到List中 client = mServerSocket.accept(); mClientList.add(client); mExecutorService.execute(new ThreadServer(client)); } } catch(Exception e) { e.printStackTrace(); } } // 每个客户端单独开启一个线程 static class ThreadServer implements Runnable { private Socket mSocket; private BufferedReader mBufferedReader; private PrintWriter mPrintWriter; private String mStrMSG; public ThreadServer(Socket socket) throws IOException { this.mSocket = socket; // 设置读取套接字客户端发送流的编码格式 mBufferedReader = new BufferedReader(new InputStreamReader( socket.getInputStream(), "GB2312")); mStrMSG = "user:" + this.mSocket.getInetAddress() + " come total:" + mClientList.size(); sendMessage(); } private void sendMessage() throws IOException { System.out.println(mStrMSG); for(Socket client : mClientList) { // 设置向套接字客户端写入流的编码格式 mPrintWriter = new PrintWriter(new OutputStreamWriter( client.getOutputStream(), "GB2312"), true); mPrintWriter.println(mStrMSG); } } public void run() { try { while((mStrMSG = mBufferedReader.readLine()) != null) { if(mStrMSG.trim().equals("exit")) { // 当一个客户端退出时 mClientList.remove(mSocket); mBufferedReader.close(); mPrintWriter.close(); mStrMSG = "user:" + this.mSocket.getInetAddress() + " exit tatal:" + mClientList.size(); mSocket.close(); sendMessage(); break; } else { mStrMSG = mSocket.getInetAddress() + ":" + mStrMSG; sendMessage(); } } } catch(Exception e) { e.printStackTrace(); } } }}
客户端
import java.io.BufferedReader;import java.io.InputStreamReader;import java.io.OutputStreamWriter;import java.io.PrintWriter;import java.net.Socket;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;public class Client2 {    private static final int PORT = 54321;    // 线程池    private static ExecutorService exec = Executors.newCachedThreadPool();    public static void main(String[] args) throws Exception {        new Client2();    }    public Client2() {        try {            Socket socket = new Socket("10.81.36.177", PORT);            exec.execute(new Sender(socket));            // 设置读取套接字服务器返回流的编码格式            BufferedReader br = new BufferedReader(new InputStreamReader(                    socket.getInputStream(), "GB2312"));            String msg;            while((msg = br.readLine()) != null) {                System.out.println(msg);            }        }        catch(Exception e) {            System.out.println(e.getMessage());        }    }    // 客户端线程获取控制台输入消息    static class Sender implements Runnable {        private Socket socket;        public Sender(Socket socket) {            this.socket = socket;        }        public void run() {            try {                BufferedReader br = new BufferedReader(new InputStreamReader(                        System.in));                // 设置向套接字服务器写入流的编码格式                PrintWriter pw = new PrintWriter(new OutputStreamWriter(                        socket.getOutputStream(), "GB2312"), true);                String msg;                while(true) {                    msg = br.readLine();                    pw.println(msg);                    if(msg.trim().equals("exit")) {                        pw.close();                        br.close();                        exec.shutdownNow();                        break;                    }                }            }            catch(Exception e) {                e.printStackTrace();            }        }    }}
手机客户端
import java.io.BufferedReader;import java.io.InputStreamReader;import java.io.OutputStreamWriter;import java.io.PrintWriter;import java.net.Socket;import android.app.Activity;import android.os.Bundle;import android.os.Handler;import android.os.Message;import android.util.Log;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.EditText;import android.widget.TextView;public class mainActivity extends Activity {    private EditText et;    private Button btn1;    private Button btn2;    private TextView tv;    private static final String SERVERIP = "10.0.2.2";    private static final int SERVERPORT = 54321;    private Thread mThread = null;    private Socket mSocket = null;    private BufferedReader mBufferedReader = null;    private PrintWriter mPrintWriter = null;    private String mStrMSG = "";    @Override    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.main);        et = (EditText) findViewById(R.id.et1);        btn1 = (Button) findViewById(R.id.btn1);        btn2 = (Button) findViewById(R.id.btn2);        tv = (TextView) findViewById(R.id.tv1);        btn1.setOnClickListener(new OnClickListener() {            @Override            public void onClick(View v) {                try {                    // 连接服务器                    mSocket = new Socket(SERVERIP, SERVERPORT);                    // 设置读取套接字服务器返回流的编码格式                    mBufferedReader = new BufferedReader(new InputStreamReader(                            mSocket.getInputStream(), "GB2312"));                    // 设置向套接字服务器写入流的编码格式                    mPrintWriter = new PrintWriter(new OutputStreamWriter(                            mSocket.getOutputStream(), "GB2312"), true);                }                catch(Exception e) {                    Log.e("", e.toString());                }            }        });        btn2.setOnClickListener(new OnClickListener() {            @Override            public void onClick(View v) {                try {                    String str = et.getText().toString() + "\n";                    mPrintWriter.print(str);                    mPrintWriter.flush();                }                catch(Exception e) {                    Log.e("", e.toString());                }            }        });        mThread = new Thread(mRunnable);        mThread.start();    }    // 线程:监听服务器发来的消息    private Runnable mRunnable = new Runnable() {        @Override        public void run() {            while(true) {                try {                    if((mStrMSG = mBufferedReader.readLine()) != null) {                        mStrMSG += "\n";                        handler.sendMessage(handler.obtainMessage());                    }                }                catch(Exception e) {                }            }        }    };    Handler handler = new Handler() {        @Override        public void handleMessage(Message msg) {            // TODO Auto-generated method stub            super.handleMessage(msg);            // 刷新            try {                tv.append(mStrMSG);            }            catch(Exception e) {                // TODO: handle exception            }        }    };}

版权声明:本文为博主原创文章,未经博主允许不得转载。

转载于:https://my.oschina.net/u/2406628/blog/473368

你可能感兴趣的文章
Oracle 备份与恢复学习笔记(5_1)
查看>>
Oracle 备份与恢复学习笔记(14)
查看>>
分布式配置中心disconf第一部(基本介绍)
查看>>
Scenario 9-Shared Uplink Set with Active/Active uplink,802.3ad(LACP)-Flex-10
查看>>
UML类图中的六种关系
查看>>
探寻Interpolator源码,自定义插值器
查看>>
一致性哈希
查看>>
mysql(待整理)
查看>>
使用PullToRefresh实现下拉刷新和上拉加载
查看>>
2012年电信业八大发展趋势
查看>>
Web日志安全分析工具 v2.0发布
查看>>
JS重载
查看>>
python2和python3同安装在Windows上,切换问题
查看>>
php加速工具xcache的安装与使用(基于LNMP环境)
查看>>
android超链接
查看>>
redhat tomcat
查看>>
统计数据库大小
查看>>
IO流的学习--文件夹下文件的复制
查看>>
第十六章:脚本化HTTP
查看>>
EXCEL表中如何让数值变成万元或亿元
查看>>