客户端群发消息功能

客户端发起请求和服务端建立连接以后,客户端写入的数据,服务端可以读取到,服务端写入的数据客户端也可以读取到,由于读取数据是一个阻塞操作,因此需要创建子线程来进行读写,首先创建一个List<Socket>来管理所有创建的客户端。服务端发消息的时候,遍历所有的客户端来给所有的客户端发送消息

                             

java端代码服务端TCPServer.java

package com.ldw.socket.server;

import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

public class TCPServer {
	
	//创建一个容器,存储客户端
	private static List<Socket> clients = new LinkedList<Socket>();

	public static void main(String[] args) {
		int port = 10002;
		try {
			ServerSocket server = new ServerSocket(port);

			while (true) {

				// 获得客户端连接
				// 阻塞式方法
				System.out.println("准备阻塞...");
				final Socket client = server.accept();
				System.out.println("阻塞完成...");
				
				// 将客户端添加到容器中
				clients.add(client);

				//开一个子线程防止阻塞,下面的内容是阻塞式的
				new Thread(new Runnable() {
					@Override
					public void run() {
						try {
							// 输入流,为了获取客户端发送的数据
							InputStream is = client.getInputStream();

							// 输出流,给客户端写数据
							OutputStream os = client.getOutputStream();

							byte[] buffer = new byte[1024];
							int len = -1;
							System.out.println("准备read...");
							while ((len = is.read(buffer)) != -1) {
								System.out.println("read完成...");

								String text = new String(buffer, 0, len);
								System.out.println(text);
								// 输出数据到客户端
								os.write("收到你的请求".getBytes());
								
								//群发:将消息转给其他用户
								for (Socket s : clients) {
									if (s != client) {
										OutputStream output = s.getOutputStream();
										output.write(text.getBytes());
									}
								}

							}
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
				}).start();

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

}

客户端通过Android来实现,布局文件,布局文件有几个按键,来方便触发

<LinearLayout 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:orientation="vertical"
    tools:context=".MainActivity" >

    <EditText
        android:id="@+id/et"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
 
	
	<Button 
	    android:text="连接"
	    android:layout_width="match_parent"
	    android:layout_height="wrap_content"
		android:onClick="clickConnect"
	    />

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="clickMessage"
        android:text="通讯" />

	<Button 
	    android:text="断开连接"
	    android:layout_width="match_parent"
	    android:layout_height="wrap_content"
		android:onClick="clickDisConnect"
	    />

</LinearLayout>

逻辑代码MainActivity.java

package org.ldw.socket.client;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

import org.ldw.socket.client.request.AuthRequest;
import org.ldw.socket.client.request.Request;
import org.ldw.socket.client.request.TextRequest;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity {
	private EditText et;
	//private EditText et_auth;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		et = (EditText) findViewById(R.id.et);
		//et_auth = (EditText) findViewById(R.id.et_auth);
	}

	private String dstName = "192.168.1.100";
	private int dstPort = 10001;
	private Socket client;
	
	public void clickConnect(View v) {
		new Thread(new Runnable() {
		@Override
		public void run() {
		
			try {
				// 三次握手
				if (client == null || client.isClosed()) {
					client = new Socket(dstName, dstPort);
				}
			
				InputStream is = client.getInputStream();
				byte[] buffer = new byte[1024];
				int len = -1;
				while ((len = is.read(buffer)) != -1) {
					final String text = new String(buffer, 0, len);
					
					runOnUiThread(new Runnable() {
						public void run() {
							Toast.makeText(getApplicationContext(), text,
							Toast.LENGTH_SHORT).show();
						}
					});
				}
			
			} catch (Exception e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
		}
		
		}
		}).start();
	}
	
	public void clickMessage(View v) {
		//获取输入框的内容
		final String content = et.getText().toString().trim();
		if (TextUtils.isEmpty(content)) {
			return;
		}
		// 数据通讯
		OutputStream os;
		try {
		os = client.getOutputStream();
		os.write(content.getBytes());
		} catch (IOException e) {
		e.printStackTrace();
		}

	}
	
	public void clickDisConnect(View v) {
		// 断开连接
		try {
			if (client != null && !client.isClosed()) {
				client.close();
				client = null;
				}
			} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值