聊天室代码(C#)

C#聊天室代码

客户端代码: using System;

using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Net;

using System.Net.Sockets; using System.Windows.Forms;

namespace EasyChat

{

public partial class login_frm : Form {

///

/// IP地址

///

private IPAddress _ipAddr;

#region 登录窗体构造函数

///

/// 构造函数,自动生成 ///

public login_frm() {

InitializeComponent(); }

#endregion

#region 登录窗体的私有方法

///

/// 验证登录信息 ///

/// 验证结果 private bool ValidateInfo()

{

if (user_tb.Text.Trim() == string.Empty) {

1

MessageBox.Show(\请填写用户名!\, \提示\,

MessageBoxButtons.OK,

MessageBoxIcon.Information); return false; }

if (!IPAddress.TryParse(svrip_tb.Text, out _ipAddr)) {

MessageBox.Show(\地址不合法!\, \提示\,

MessageBoxButtons.OK, MessageBoxIcon.Information); return false; }

int _port;

if (!int.TryParse(svrport_tb.Text, out _port)) {

MessageBox.Show(\端口号不合法!\, \提示\,

MessageBoxButtons.OK, MessageBoxIcon.Information); return false; } else

{

if (_port < 1024 || _port > 65535) {

MessageBox.Show(\端口号不合法!\, \提示\,

MessageBoxButtons.OK,

MessageBoxIcon.Information); return false; }

}

return true; }

///

/// 取消,关闭窗体 ///

///

private void cancel_btn_Click(object sender, EventArgs e) 2

{

this.Close(); }

///

/// 登录

///

///

private void login_btn_Click(object sender, EventArgs e) {

//验证数据合法性 if (!ValidateInfo()) { return; }

int port = int.Parse(svrport_tb.Text); //向服务器发出连接请求

TCPConnection conn = new TCPConnection(_ipAddr, port); TcpClient _tcpc = conn.Connect(); if (_tcpc == null)

{

MessageBox.Show(\无法连接到服务器,请重试!\, \错误\,

MessageBoxButtons.OK, MessageBoxIcon.Exclamation); }

else {

NetworkStream netstream = _tcpc.GetStream();//提供用于访问网络的基本数据流 //向服务器发送用户名以确认身份

netstream.Write(Encoding.Unicode.GetBytes(user_tb.Text), Encoding.Unicode.GetBytes(user_tb.Text).Length); //得到登录结果

byte[] buffer = new byte[50];

netstream.Read(buffer, 0, buffer.Length);//该方法将数据读入 buffer 参数并返回成功读取的字节数。如果没有可以读取的数据,则 Read 方法返回 0。

string connResult = Encoding.Unicode.GetString(buffer).TrimEnd('\\0'); if (connResult.Equals(\))

{

MessageBox.Show(\您的用户名已经被使用,请尝试其他用户名!\, \提示\,

MessageBoxButtons.OK,

MessageBoxIcon.Information);

0,

3

联系客服:779662525#qq.com(#替换为@) 苏ICP备20003344号-4