C#作为服务器端 android作为客户端当服务器连接多个客户端的时候 服务器端只能接收最后一个客户端发过来的 数据,其他客户端向服务器发送数据服务器端就收不到
//服务端代码
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.Net;
using System.Net.Sockets;
using System.Collections;
namespace TCPServer
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
//以下声明代码很乱
public bool btnstatu = true; //开始停止服务按钮状态
public Thread myThread; //声明一个线程实例
public Socket newsock; //声明一个Socket实例
public Socket server1;
public Socket Client;
public delegate void MyInvoke(string str); //用委托的方式来更新控件,线程安全
public string str = "192.168.0.222";
public IPAddress ipa;
public IPAddress ClientIP;
public int ClientPORT;
public string ClientName;
public IPEndPoint localEP;
public int localPort;
public EndPoint remote;
public Hashtable _sessionTable; //哈希表用来存储所有连接进来的Socket的ip和port
//字典用来存储Socket实例的信息,方便发送时使用
public Dictionary<string,Socket> dicSocket = new Dictionary<string, Socket>();
public bool m_Listening;
//用来设置服务端监听的端口号
public int setPort
{
get { return localPort; }
set { localPort = value; }
}
//用来往richtextbox框中显示消息
public void showClientMsg(string msg)
{
//在线程里以安全方式调用控件
if (showinfo.InvokeRequired)
{
MyInvoke _myinvoke = showClientMsg;
showinfo.Invoke(_myinvoke, new object[] { msg });
}
else
{
showinfo.AppendText(msg);
}
}
public void userListOperate(string msg)
{
//在线程里以安全方式调用控件
if (userList.InvokeRequired)
{
MyInvoke _myinvoke = userListOperate;
userList.Invoke(_myinvoke, new object[] { msg });
}
else
{
userList.Items.Add(msg);
cmbUserList.Items.Add(msg);
}
}
public void userListOperateR(string msg)
{
//在线程里以安全方式调用控件
if (userList.InvokeRequired)
{
MyInvoke _myinvoke = userListOperateR;
userList.Invoke(_myinvoke, new object[] { msg });
}
else
{
cmbUserList.Items.Remove(msg);
userList.Items.Remove(msg);
}
}
//监听函数
public void Listen()
{ //设置端口
setPort=int.Parse(serverport.Text.Trim());
//初始化SOCKET实例
newsock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//允许SOCKET被绑定在已使用的地址上。
newsock.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
//初始化终结点实例
ipa = IPAddress.Parse(str);
localEP=new IPEndPoint(ipa,setPort);
try
{
_sessionTable = new Hashtable(53);
//绑定
newsock.Bind(localEP);
//监听
newsock.Listen(10);
//开始接受连接,异步。
newsock.BeginAccept(OnConnectRequest, newsock);
}
catch (Exception ex)
{
showClientMsg(ex.Message);
}
}
//当有客户端连接时的处理
public void OnConnectRequest(IAsyncResult ar)
{
//初始化一个SOCKET,用于其它客户端的连接
server1 = (Socket)ar.AsyncState;
//将接收到的Socket传给Client,然后继续监听
Client = server1.EndAccept(ar);
//将要发送给连接上来的客户端的提示字符串
DateTimeOffset now = DateTimeOffset.Now;
string strDateLine = "欢迎登录到服务器" + "\r\n";
byte[] byteDateLine = Encoding.UTF8.GetBytes(strDateLine);
//将提示信息发送给客户端,并在服务端显示连接信息。
ClientIP = (Client.RemoteEndPoint as IPEndPoint).Address;
ClientPORT = (Client.RemoteEndPoint as IPEndPoint).Port;
ClientName = "IP:" + ClientIP + "Port:" + ClientPORT;
showClientMsg(Client.RemoteEndPoint + "连接成功。" + now.ToString("G") + "\r\n");
//将欢迎信息发送给连接进来的客户端
Client.Send(byteDateLine, byteDateLine.Length, 0);
//将连接进来的客户端ip和端口号显示在控件上
userListOperate(ClientName);
//将连接进来的客户端Socket实例存进字典
dicSocket.Add(ClientName, Client);
//把连接成功的客户端的SOCKET实例放入哈希表
_sessionTable.Add(Client.RemoteEndPoint, null);
//等待新的客户端连接
server1.BeginAccept(OnConnectRequest, server1);
int byteLen;
try
{
while (true)
{
//定义收到的字节流的长度,Available为获取从网络接收到的可供读取的数据量
byteLen = Client.Available;
//创建缓冲区,后面[ ]里的整数为设定的缓冲区大小,C#必须手动设定大小
byte[] bytes = new byte[1024];
//接受信息
Client.Receive(bytes, byteLen, SocketFlags.None);
//判断客户端有没有发送消息过来
if (byteLen == 0)
{
continue;
}
string stringdata = Encoding.UTF8.GetString(bytes).Substring(0, byteLen);
Console.WriteLine("收到消息: " + stringdata + "\r\n");
string ip = Client.RemoteEndPoint.ToString();
if (stringdata == "STOP")
{
//当客户端终止连接时
showClientMsg(ip + " " + now.ToString("G") + " " + "已从服务器断开" + "\r\n");
_sessionTable.Remove(Client.RemoteEndPoint);
break;
}
//显示客户端发送过来的信息
showClientMsg(ip + "说: " + stringdata + "\r\n");
}
}
catch (SocketException)
{
MessageBox.Show("1");
}
catch (ArgumentException)
{
MessageBox.Show("2");
}
}
//以下实现发送广播消息
public void SendBroadMsg()
{
string strDataLine = sendmsg.Text + "\r\n";
byte[] sendData = Encoding.UTF8.GetBytes(strDataLine);
try
{
//遍历所有客户端
//for(int i=0;i<userList.Items.Count;i++)
//{
// dicSocket[userList.Items[i].ToString()].Send(sendData);
//}
//选择单个客户端发送
dicSocket[cmbUserList.SelectedItem.ToString()].Send(sendData);
//网上教用foreach遍历发送广播消息,但是自己用的时候遍历只能发给最新接入的Socket,所以改用for循环发送
//foreach (DictionaryEntry de in _sessionTable)
//{
// EndPoint temp = (EndPoint) de.Key;
// Console.WriteLine("发送成功" + strDataLine);
// Client.SendTo(sendData, temp);
//}
}
catch (ArgumentNullException e)
{
Console.WriteLine(e);
}
showClientMsg("我说: " + sendmsg.Text + "\r\n");
sendmsg.Text = "";
}
//开始停止服务按钮
private void startService_Click(object sender, EventArgs e)
{
//新建一个委托线程
ThreadStart myThreadDelegate = Listen;
//实例化新线程
myThread = new Thread(myThreadDelegate);
if (btnstatu)
{
myThread.Start();
statuBar.Text = "服务已启动,等待客户端连接";
btnstatu = false;
startService.Text = "停止服务";
}
else
{
//停止服务(绑定的套接字没有关闭,因此客户端还是可以连接上来)
myThread.Interrupt();
myThread.Abort();
//showClientMsg("服务器已停止服务"+"\r\n");
btnstatu = true;
startService.Text = "开始服务";
statuBar.Text = "服务已停止";
}
}
//窗口关闭时中止线程。
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (myThread != null)
{
myThread.Abort();
}
}
private void send_Click(object sender, EventArgs e)
{
SendBroadMsg();
}
}
}