局域网聊天小程序C#代码.docx

上传人:牧羊曲112 文档编号:3479213 上传时间:2023-03-13 格式:DOCX 页数:4 大小:37.37KB
返回 下载 相关 举报
局域网聊天小程序C#代码.docx_第1页
第1页 / 共4页
局域网聊天小程序C#代码.docx_第2页
第2页 / 共4页
局域网聊天小程序C#代码.docx_第3页
第3页 / 共4页
局域网聊天小程序C#代码.docx_第4页
第4页 / 共4页
亲,该文档总共4页,全部预览完了,如果喜欢就下载吧!
资源描述

《局域网聊天小程序C#代码.docx》由会员分享,可在线阅读,更多相关《局域网聊天小程序C#代码.docx(4页珍藏版)》请在三一办公上搜索。

1、局域网聊天小程序C#代码局域网聊天小程序C#版代码 using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Net; using System.Net.Sockets; using System.Threading; namespace ChatP2P public partial class Ma

2、inForm : Form public MainForm InitializeComponent; CheckForIllegalCrossThreadCalls = false; TcpListener listener;/监听器对象 private void button3_Click(object sender, EventArgs e) Thread th = new Thread(new ThreadStart(StarReceiveMsg); th.Start;/开始监听进程,在后台运行 / / 接收聊天信息的方法 / private void StarReceiveMsg in

3、t port; try port = int.Parse(txtThisPort.Text); catch MessageBox.Show(端口号请输入数字!); return; listener = new TcpListener(port); try listener.Start;/开始监听 catch /如果端口已经被占用将会报错。 MessageBox.Show(端口已被占用,请使用其它端口); return; while (true)/确保监听器一直在后台运行,所以用死循环 TcpClient client = null; try client = listener.AcceptTc

4、pClient;/监听远程连接 catch /如果点击停止将报错,停止监听 return; NetworkStream ns = client.GetStream;/创建NetworkStream对象 byte data = new byte1000;/定义接收数据的二进制数组 ns.Read(data, 0, 1000);/接收数据,数据有限制,最多只能接收1000个字节,如果要接收更多数据需要用循环读取 txtChatMsg.Text = Encoding.Unicode.GetString(data);/将接收到的数据转为字符串,并显示到文本框中 ns.Close;/关闭流对象 clie

5、nt.Close;/关闭client对象,以便下一次监听数据 private void SendMsg TcpClient client = new TcpClient; client.Connect(txtThatIP.Text, int.Parse(txtThatPort.Text);/连接到远程IP NetworkStream ns = client.GetStream; byte data = new byte1000;/创建存储数据的byte数组 data = Encoding.Unicode.GetBytes(txtMsg.Text);/将文本框中的字符串读取到byte数据中 ns

6、.Write(data, 0, data.Length);/将数据写入到net流 ns.Flush;/提交数据 ns.Close;/关闭流 client.Close;/关闭client private void button2_Click(object sender, EventArgs e) /测试是否可以连接 try TcpClient client = new TcpClient; client.Connect(txtThatIP.Text, int.Parse(txtThatPort.Text); client.Close; MessageBox.Show(连接成功,可以发送聊天消息); catch MessageBox.Show(连接失败); private void button1_Click(object sender, EventArgs e) SendMsg; private void button4_Click(object sender, EventArgs e) listener.Stop;/停止监听器

展开阅读全文
相关资源
猜你喜欢
相关搜索

当前位置:首页 > 生活休闲 > 在线阅读


备案号:宁ICP备20000045号-2

经营许可证:宁B2-20210002

宁公网安备 64010402000987号