Socket聊天程序(Client)

 

 今天在VS2010上做点练习,用Socket编程写的聊天程序。

长的比较丑

 

这是客户端的主要代码: 

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net.Sockets;
using System.Net;
using System.Threading;

namespace _01_socketclient
{
	public partial class SocketClient : Form
	{
		Socket socketClient = null;		//客户端套接字
		bool connectioned = false;		//连接断开标识
		Thread sendThread = null;		//发送线程
		Thread receiveThread = null;	//接受线程
		delegate void SetTextCallback(string text);//invoke的方式实现安全调用
		delegate void ClearTextCallback();

		public SocketClient()
		{
			InitializeComponent();
		}

		private void btnConnection_Click(object sender, EventArgs e)
		{
			if (connectioned)
			{
				//结束接受线程
				if (receiveThread.IsAlive)
					receiveThread.Abort();
				//关闭套接字
				socketClient.Close();
				ShowMsg("断开连接。");

				btnConnection.Text = "Connection";
				connectioned = false;
				//设置发送不可用
				btnSend.Enabled = connectioned;
			}
			else
			{
				//创建客户端套接字
				socketClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

				IPAddress adress = null;
				IPEndPoint endpoint = null;

				try
				{
					//IP不为空
					adress = IPAddress.Parse(txtIP.Text.Trim());
				}
				catch
				{
					//IP为空
					txtIP.Text = "192.168.1.100";
				}
				try
				{
					//PORT不为空
					endpoint = new IPEndPoint(adress, int.Parse(txtPort.Text.Trim()));
				}
				catch
				{
					//PORT为空
					txtPort.Text = "52113";
				}
				//连接服务器
				try
				{
					ShowMsg("连接到 " + txtIP.Text.ToString() + ":" + txtPort.Text.ToString());
					socketClient.Connect(endpoint);
					ShowMsg("成功连接到服务器。");
				}
				catch
				{
					ShowMsg("连接服务器失败。");
					return;
				}

				//实例接收线程
				receiveThread = new Thread(new ThreadStart(RecevieThread));
				//设置为后台线程
				receiveThread.IsBackground = true;
				//启动接受线程
				receiveThread.Start();

				btnConnection.Text = "Broke";
				connectioned = true;
				//设置发送可用
				btnSend.Enabled = connectioned;

			}//else

		}

		/// <summary>
		/// 显示文本信息
		/// </summary>
		/// <param name="msg"></param>
		private void ShowMsg(string msg)
		{
			if (txtShow.InvokeRequired)
			{

				SetTextCallback d = new SetTextCallback(ShowMsg); ;
				Invoke(d, new object[] { msg });
			}
			else
			{
				txtShow.AppendText(msg + "\r\n");
			}
		}

		private void SendTextClear()
		{
			if (txtSend.InvokeRequired)
			{
				ClearTextCallback d = new ClearTextCallback(SendTextClear);
				Invoke(d);
			}
			else
				txtSend.Clear();

		}

		/// <summary>
		/// 发送线程函数
		/// </summary>
		private void SendThread()
		{

			if (txtSend.Text.ToString() == "")
			{
				MessageBox.Show("发送内容不能为空!");
			}
			else
			{
				//获取发送字符数组
				byte[] arrSend = System.Text.Encoding.Default.GetBytes(txtSend.Text.ToString());
				//回显发送内容
				ShowMsg(txtSend.Text.ToString());
				//清空发送区
				SendTextClear();
				try
				{
					//发送信息
					socketClient.Send(arrSend);
				}
				catch
				{
					ShowMsg("服务器已关闭。");
					//关闭服务端套接字
					socketClient.Close();
				}

			}
			sendThread.Abort();
			MessageBox.Show("sendThread dead");

		}

		/// <summary>
		/// 接收线程执行方法
		/// </summary>
		private void RecevieThread()
		{
			while (true)
			{
				byte[] arrRec = new byte[1024 * 1024 * 2];
				int num = 0;

				try
				{
					num = socketClient.Receive(arrRec);
					string strMsg = socketClient.RemoteEndPoint.ToString();
					strMsg += ":" + System.Text.Encoding.Default.GetString(arrRec, 0, num);
					ShowMsg(strMsg);
				}
				catch
				{
					//ShowMsg("连接已断开。");
					socketClient.Close();
					return;
				}

			}//while
		}

		/// <summary>
		/// 发送按钮
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void btnSend_Click(object sender, EventArgs e)
		{
			//绑定发送线程函数
			sendThread = new Thread(new ThreadStart(SendThread));
			//设置为后台线程
			sendThread.IsBackground = true;
			//启动发送线程
			sendThread.Start();

		}
	}
}

 

 

-The End-

© Jervis

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值