聊天室

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();
}

posted @ 2018-08-06 08:14  真是善良  阅读(112)  评论(0编辑  收藏  举报