聊天室

public Form1()
{
InitializeComponent();
CheckForIllegalCrossThreadCalls = false;
}
TcpListener tcpl = null;
bool serverState = true;
Thread thd;
/// <summary>
/// 加载时关闭按钮不可用
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Form1_Load(object sender, EventArgs e)
{
button2.Enabled = false;
}
/// <summary>
/// 开启监听
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button1_Click(object sender, EventArgs e)
{
IPAddress ip = IPAddress.Parse("172.25.46.9");//地址
tcpl = new TcpListener(ip, 9000);//声明一个监听服务
tcpl.Start();//监听服务
thd = new Thread(new ThreadStart(TcpListenerClient));//声明线程开启监听
thd.Start();//监听开启
serverState = true;
button1.Enabled = false;
button2.Enabled = true;
}
/// <summary>
/// 接收线程
/// </summary>
void TcpListenerClient()
{
int i = 0;
while(serverState)//根据服务状态
{
i++;
TcpClient client = tcpl.AcceptTcpClient();//接收
NetworkStream stream = client.GetStream();//网络流,获取数据
byte[] arr = new byte[client.ReceiveBufferSize];//保存到字节数组
stream.Read(arr, 0, arr.Length);//从流中读取
var values = "";
//if (i == 1)//第一次加载
//{
// values = "对方说:" + System.Text.Encoding.Default.GetString(arr);
//}
//else
//{
// values = "对方说:" + System.Text.Encoding.Default.GetString(arr);
//}
values = "对方说:" + System.Text.Encoding.Default.GetString(arr);
richTextBox1.AppendText(values+" \r\n ");//显示到富文本框
}

}
/// <summary>
/// 关闭监听
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button2_Click(object sender, EventArgs e)
{
try
{
serverState = false;
button1.Enabled = true;
button2.Enabled = false;
tcpl.Stop();
if(thd.ThreadState==ThreadState.Running)//关闭线程
{
thd.Abort();
}
}
catch (Exception)
{

throw;
}
}
/// <summary>
/// 发送
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button3_Click(object sender, EventArgs e)
{
TcpClient client = new TcpClient("172.25.46.21", 9191);//对方的IP地址和端口号保存在客户端连接
NetworkStream stream = client.GetStream();//保存到网络流
byte[] arr = System.Text.Encoding.Default.GetBytes(textBox1.Text);//将文本框的文本转化为字节数组
stream.Write(arr, 0, arr.Length);//写入流
richTextBox1.AppendText("提哥说:" + textBox1.Text + " \r\n ");
textBox1.Text = "";
stream.Flush();
stream.Close();
client.Close();
}

转载于:https://www.cnblogs.com/JXSBoKeYuan/p/9428233.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值