C# Socket 编写的简单聊天通信程序(客户端+服务端)

kidzss

贡献于2013-04-17

字数:4030 关键词: .NET开发 C#

服务端:     需要增加的命名空间: using System.Threading; using System.Net; using System.Net.Sockets;     以下是具体实现。 C# code复制代码 namespace TCPServer { public partial class Form1 : Form { public Form1() { InitializeComponent(); } public bool btnstatu = true; //开始停止服务按钮状态 public Thread myThread; //声明一个线程实例 public Socket newsock; //声明一个Socket实例 public Socket Client; public IPEndPoint localEP; public int localPort; public bool m_Listening; //用来设置服务端监听的端口号 public int setPort { get { return localPort; } set { localPort = value; } } //用来往richtextbox框中显示消息 public void showClientMsg(string msg) { showClientMsg(msg+"\r\n"); } //监听函数 public void Listen() { //设置端口 setPort=int.Parse(serverport.Text.Trim()); //初始化SOCKET实例 newsock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //初始化终结点实例 localEP=new IPEndPoint(IPAddress.Any,setPort); try { //绑定 newsock.Bind(localEP); //监听 newsock.Listen(10); //用于设置按钮状态 m_Listening = true; //开始接受连接,异步。 newsock.BeginAccept(new AsyncCallback(OnConnectRequest), newsock); } catch (Exception ex) { showClientMsg(ex.Message); } } //当有客户端连接时的处理 public void OnConnectRequest(IAsyncResult ar) { //初始化一个SOCKET,用于其它客户端的连接 Socket server1 = (Socket)ar.AsyncState; Client = server1.EndAccept(ar); //将要发送给连接上来的客户端的提示字符串 string strDateLine = "Welcome here"; Byte[] byteDateLine = System.Text.Encoding.ASCII.GetBytes(strDateLine); //将提示信息发送给客户端 Client.Send(byteDateLine, byteDateLine.Length, 0); //等待新的客户端连接 server1.BeginAccept(new AsyncCallback(OnConnectRequest), server1); while (true) { int recv = Client.Receive(byteDateLine); string stringdata = Encoding.ASCII.GetString(byteDateLine, 0, recv); DateTimeOffset now = DateTimeOffset.Now; //获取客户端的IP和端口 string ip = Client.RemoteEndPoint.ToString(); if (stringdata == "STOP") { //当客户端终止连接时 showinfo.AppendText(ip+"已从服务器断开"); break; } //显示客户端发送过来的信息 showinfo.AppendText(ip + " " + now.ToString("G") + " " + stringdata + "\r\n"); } } //开始停止服务按钮 private void startService_Click(object sender, EventArgs e) { //新建一个委托线程 ThreadStart myThreadDelegate = new ThreadStart(Listen); //实例化新线程 myThread = new Thread(myThreadDelegate); if (btnstatu) { myThread.Start(); statuBar.Text = "服务已启动,等待客户端连接"; btnstatu = false; startService.Text = "停止服务"; } else { //停止服务(功能还有问题,无法停止) m_Listening = false; newsock.Close(); myThread.Abort(); showClientMsg("服务器停止服务"); btnstatu = true; startService.Text = "开始服务"; statuBar.Text = "服务已停止"; m_Listening = false; } } //窗口关闭时中止线程。 private void Form1_FormClosing(object sender, FormClosingEventArgs e) { if (myThread != null) { myThread.Abort(); } } } } 客户端: C# code复制代码 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; using System.Net.Sockets; using System.Threading; namespace TCPClient { public partial class Form1 : Form { public Socket newclient; public bool Connected; public Thread myThread; public delegate void MyInvoke(string str); public Form1() { InitializeComponent(); } public void Connect() { byte[] data = new byte[1024]; newclient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); string ipadd = serverIP.Text.Trim(); int port = Convert.ToInt32(serverPort.Text.Trim()); IPEndPoint ie = new IPEndPoint(IPAddress.Parse(ipadd), port); try { newclient.Connect(ie); connect.Enabled = false; Connected = true; } catch(SocketException e) { MessageBox.Show("连接服务器失败 "+e.Message); return; } ThreadStart myThreaddelegate = new ThreadStart(ReceiveMsg); myThread = new Thread(myThreaddelegate); myThread.Start(); } public void ReceiveMsg() { while (true) { byte[] data = new byte[1024]; int recv = newclient.Receive(data); string stringdata = Encoding.UTF8.GetString(data, 0, recv); showMsg(stringdata + "\r\n"); //receiveMsg.AppendText(stringdata + "\r\n"); } } public void showMsg(string msg) { { //在线程里以安全方式调用控件 if (receiveMsg.InvokeRequired) { MyInvoke _myinvoke = new MyInvoke(showMsg); receiveMsg.Invoke(_myinvoke, new object[] { msg }); } else { receiveMsg.AppendText(msg); } } } private void SendMsg_Click(object sender, EventArgs e) { int m_length = mymessage.Text.Length; byte[] data=new byte[m_length]; data = Encoding.UTF8.GetBytes(mymessage.Text); int i = newclient.Send(data); showMsg("我说:" + mymessage.Text + "\r\n"); //receiveMsg.AppendText("我说:"+mymessage.Text + "\r\n"); mymessage.Text = ""; //newclient.Shutdown(SocketShutdown.Both); } private void connect_Click(object sender, EventArgs e) { Connect(); } }

下载文档,方便阅读与编辑

文档的实际排版效果,会与网站的显示效果略有不同!!

需要 3 金币 [ 分享文档获得金币 ]
1 人已下载

下载文档

相关文档