个人随笔
技术改变世界

C# 异步TCP Socket聊天室

该例子是一个异步TCP Socket聊天室!
1个服务器
N个客户端
下载下来后,直接将本机的IP改为192.168.1.224即可直接运行程序,或者自行改下程序源码中指定的IP地址即可
—————————-
图:
AsyncTcp
服务器+客户端代码大概有800来行,下面贴出一部分代码。
下面我会贴出下载地址的!
先贴代码(部分)吧:

/// <summary>  
/// 异步发送message给user  
/// </summary>  
/// <param name="user"></param>  
/// <param name="message"></param>
private void AsyncSendToClient(User user, string message)  
{  
    SendToClientDelegate d = new SendToClientDelegate(SendToClient);  
    IAsyncResult result = d.BeginInvoke(user, message, null, null);  
    while (result.IsCompleted == false)  
    {  
        if (isExit)  
            break;  
        Thread.Sleep(250);  
    }  
    d.EndInvoke(result);  
}  
  
private delegate void SendToClientDelegate(User user, string message);  
/// <summary>  
/// 发送message给user  
/// </summary>  
/// <param name="user"></param>  
/// <param name="message"></param>
private void SendToClient(User user, string message)  
{  
    try  
    {  
        //将字符串写入网络流,此方法会自动附加字符串长度前缀  
        user.bw.Write(message);  
        user.bw.Flush();  
        AddItemToListBox(string.Format("向[{0}]发送:{1}", user.userName, message));  
    }  
    catch  
    {  
        AddItemToListBox(string.Format("向[{0}]发送信息失败", user.userName));  
    }  
}  
  
/// <summary>  
/// 移除用户  
/// </summary>  
/// <param name="user"></param>
private void RemoveUser(User user)  
{  
    userList.Remove(user);  
    user.Close();  
    AddItemToListBox(string.Format("当前连接用户数:{0}", userList.Count));  
}  
  
delegate void ReceiveMessageDelegate(User user, out string receiveMessage);  
/// <summary>  
/// 接收客户端发来的信息  
/// </summary>  
/// <param name="user"></param>  
/// <param name="receiveMessage"></param>
private void ReceiveMessage(User user, out string receiveMessage)  
{  
    try  
    {  
        receiveMessage = user.br.ReadString();  
    }  
    catch (Exception ex)  
    {  
        AddItemToListBox(ex.Message);  
        receiveMessage = null;  
    }  
}  
  
private delegate void ListenClientDelegate(out TcpClient client);  
/// <summary>  
/// 接受挂起的客户端连接请求  
/// </summary>  
/// <param name="newClient"></param>
private void ListenClient(out TcpClient newClient)  
{  
    try  
    {  
        newClient = myListener.AcceptTcpClient();  
    }  
    catch  
    {  
        newClient = null;  
    }  
}  
  
delegate void AddItemToListBoxDelegate(string str);  
/// <summary>  
/// 在ListBox中追加状态信息  
/// </summary>  
/// <param name="str">要追加的信息</param>
private void AddItemToListBox(string str)  
{  
    if (lst_Status.InvokeRequired)  
    {  
        AddItemToListBoxDelegate d = AddItemToListBox;  
        lst_Status.Invoke(d, str);  
    }  
    else  
    {  
        lst_Status.Items.Add(str);  
        lst_Status.SelectedIndex = lst_Status.Items.Count - 1;  
        lst_Status.ClearSelected();  
    }  
}

完整代码包下载地址(包含客户端和服务器):AsyncTcp

转载请注明出处王旭博客 » C# 异步TCP Socket聊天室

分享到:更多 ()

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址