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

初学C#的SOCKET编程,照着网上的代码写下来,程序总是有问题,经过自己长时间的调试,完成程序,以下是原码,有需要可以参考一下,还不完善,欢迎大家批评指正。 (这里的代码没更新,附件重新上传更新,在另一个线程中使用委托来修改控件的属性,发送广播功能还有问题,稍修更新修正。) 
环境:VS2008 .NET3.5
     网上给出的程序都是控制台程序,我这个是WINFORM程序。有详细的说明,以服务端程序。
服务端:
    需要增加的命名空间:
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();
                }
                
        }
}
  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是C# Socket通信客户端服务端的例子: 服务端: ```csharp using System; using System.Net; using System.Net.Sockets; using System.Text; public class Server { public static void Main() { byte[] bytes = new byte[1024]; IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName()); IPAddress ipAddress = ipHostInfo.AddressList[0]; IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000); Socket listener = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp); try { listener.Bind(localEndPoint); listener.Listen(10); while (true) { Console.WriteLine("Waiting for a connection..."); Socket handler = listener.Accept(); string data = null; while (true) { bytes = new byte[1024]; int bytesRec = handler.Receive(bytes); data += Encoding.ASCII.GetString(bytes, 0, bytesRec); if (data.IndexOf("<EOF>") > -1) { break; } } Console.WriteLine("Text received : {0}", data); byte[] msg = Encoding.ASCII.GetBytes(data); handler.Send(msg); handler.Shutdown(SocketShutdown.Both); handler.Close(); } } catch (Exception e) { Console.WriteLine(e.ToString()); } Console.WriteLine("\nPress ENTER to continue..."); Console.Read(); } } ``` 客户端: ```csharp using System; using System.Net; using System.Net.Sockets; using System.Text; public class Client { public static void Main() { byte[] bytes = new byte[1024]; try { IPHostEntry ipHostInfo = Dns.GetHostEntry("localhost"); IPAddress ipAddress = ipHostInfo.AddressList[0]; IPEndPoint remoteEP = new IPEndPoint(ipAddress, 11000); Socket sender = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp); try { sender.Connect(remoteEP); Console.WriteLine("Socket connected to {0}", sender.RemoteEndPoint.ToString()); byte[] msg = Encoding.ASCII.GetBytes("This is a test<EOF>"); int bytesSent = sender.Send(msg); int bytesRec = sender.Receive(bytes); Console.WriteLine("Echoed test = {0}", Encoding.ASCII.GetString(bytes, 0, bytesRec)); sender.Shutdown(SocketShutdown.Both); sender.Close(); } catch (ArgumentNullException ane) { Console.WriteLine("ArgumentNullException : {0}", ane.ToString()); } catch (SocketException se) { Console.WriteLine("SocketException : {0}", se.ToString()); } catch (Exception e) { Console.WriteLine("Unexpected exception : {0}", e.ToString()); } } catch (Exception e) { Console.WriteLine(e.ToString()); } Console.WriteLine("\nPress ENTER to continue..."); Console.Read(); } } ``` 这里的例子中,服务端监听本机IP地址和端口11000的连接请求,客户端连接服务端并向服务端发送数据,服务端收到数据并将其原样返回给客户端

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值