Socket服务端实现

监听类

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

/**
 * 监听类
 * Created by user on 2016/11/8.
 */
public class SocketListener extends Thread {
    ServerSocket serverSocket;
    Socket socket;

    @Override
    public void run() {
        super.run();
        try {
            serverSocket = new ServerSocket(12345);
            //死循环,保证服务端不断地监听
            while (true) {
                /**
                 * 该方法为阻塞方法
                 *  等待监听是否有客户端链接
                 *  一旦有客户端连接到服务端,代码才会继续执行
                 */
                socket = serverSocket.accept();
                System.out.println("有客户端连接成功");
                ChatSocket chatSocket = new ChatSocket(socket);
//                把创建出来的聊天类对象放入到manager的集合中
                SocketManager.getInstance().add(chatSocket);
                chatSocket.start();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

用命令行验证是否连接成功,telnet localhost是建立本地连接,“12345”是端口号
Socket服务端实现_第1张图片
聊天类

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

/**
 * 聊天类
 * 1.调用write的方法的时候,忘服务器发送数据
 * 2.只要聊天类已创建,服务端就要一直从客户端获取数据,看是否有数据发动过来
 * Created by user on 2016/11/8.
 */
public class ChatSocket extends Thread {
    Socket socket;

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

    @Override
    public void run() {
        super.run();
        try {
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(socket.getInputStream(), "UTF-8"));
            String line = null;
            while ((line = reader.readLine()) != null) {
                SocketManager.getInstance().publish(this,line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void write(String str) {
        try {
            /**
             * 1.从socket中获取到输出的字节流
             * 2.要把字节流转换成字符流(BufferedWriter)
             * 3.字节流转换成字符流需要用到一个writer的类进行转换
             */
            BufferedWriter writer = new BufferedWriter(
                    new OutputStreamWriter(socket.getOutputStream(), "UTF-8"));
            //注意:在写出的时候要给写出的内容加一个\n,然后调用flush进行发送
            writer.write(str + "\n");
            writer.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

管理类

import java.util.Vector;

/**
 * 管理类
 * 1.管理聊天类对象
 * 2.转发数据
 * Created by user on 2016/11/8.
 */
public class SocketManager {
    /**
     * vector和list 都是数据集合
     * vector 是线程安全的
     * list   是线程不安全
     */
    Vector chatSockets = new Vector<>();
    /**
     * managet需要使用单例
     * 需要使用懒汉式
     * 以为懒汉式是线程安全的方式
     */
    private static final SocketManager manager = new SocketManager();
    private SocketManager() {
    }
    public static SocketManager getInstance() {
        return manager;
    }

    //往manager的集合中存入一个聊天天对象
    public void add(ChatSocket chatSocket) {
        chatSockets.add(chatSocket);
    }

    /**
     * 转发功能
     * chatSocket  发送数据的聊天类对象
     * str         发出的数据
      */

    public void publish(ChatSocket chatSocket, String str) {
        for (int i = 0; i < chatSockets.size(); i++) {
            ChatSocket cs = chatSockets.get(i);
            if (!chatSocket.equals(cs)) {
                cs.write(str);
            }
        }
    }
}

Socket服务端实现_第2张图片

下面是客户端代码

package com.baozilichao.mysocketclient;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.EditText;
import android.widget.TextView;

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

public class MainActivity extends Activity {
    EditText et;
    TextView tv;
    BufferedWriter writer;
    BufferedReader reader;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_main);
        et = (EditText) findViewById(R.id.et);
        tv = (TextView) findViewById(R.id.tv);
        findViewById(R.id.connect).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                connect();
            }
        });
        findViewById(R.id.send).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                send();
            }
        });
    }

    public void connect() {
        new AsyncTask() {
            @Override
            protected String doInBackground(String... strings) {
                try {
                    Socket socket = new Socket("***.**.**.***", 12345);
                    writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), "UTF-8"));
                    reader = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8"));
                    publishProgress("链接成功");
                    String line = null;
                    while ((line = reader.readLine()) != null) {
                        publishProgress(line);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return null;
            }

            @Override
            protected void onProgressUpdate(String... values) {
                tv.append("对方说的内容:" + values[0] + "\n");
            }
        }.execute();

    }

    public void send() {
        try {
            writer.write(et.getText().toString() + "\n");
            writer.flush();
            tv.append("我说的内容"+et.getText().toString()+"\n");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Socket服务端实现_第3张图片

你可能感兴趣的:(小知识点,Java)