Socket实例

服务器端代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

using System.Threading;
using System.Net;
using System.Net.Sockets;

namespace ChatToolServer
{
    public partial class Form1 : Form
    {
        //server-用于处理客户端连接请求的socket
        Socket clientSocket = null;
        delegate void del();
    
        public Form1()
        {
            InitializeComponent();
        }
        //server-侦听方法
        private void listen()
        {
            //获取服务器IP
            string hostName = Dns.GetHostName();
            IPAddress[] ip = Dns.GetHostAddresses(hostName);
            IPAddress HostIp = ip[0];

            //创建一个网络端点
            IPEndPoint iep = new IPEndPoint(HostIp, 82);

            //创建服务端服务端套接字
            Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            //将套接字与网络端点绑定
            serverSocket.Bind(iep);

            //将套接字置为侦听状态,并设置最大队列数为10
            serverSocket.Listen(10);

            //以同步方式从侦听套接字的连接请求队列中提取第一个挂起的连接请求,然后创建并返回新的 Socket
            //新的套接字:包含对方计算机的IP和端口号,可使用这个套接字与本机进行通信  
            clientSocket = serverSocket.Accept();
            if (clientSocket != null)
            {
                MessageBox.Show("连接成功!");
            }
           
        }

        private void send_Click(object sender, EventArgs e)
        {
            if (this.textBox1.Text != "")//不能发送空消息
            {             
                    try
                    {
                        //发送数据
                        string message = textBox1.Text;
                        byte[] sendbytes = System.Text.Encoding.UTF8.GetBytes(message);
                        int successSendBtyes = clientSocket.Send(sendbytes, sendbytes.Length, SocketFlags.None);
                    }
                    catch (Exception exp)
                    {
                        MessageBox.Show(exp.Message);
                    }
                    //将发送的数据显示到对话窗口并使对话窗口的滚动条一直停留在最下方
                    this.textBox2.Text +="服务器:"+"/r/n" +textBox1.Text + "/r/n";//发完一条消息就换行显示
                    this.textBox2.SelectionStart = this.textBox2.Text.Length;
                    this.textBox2.ScrollToCaret();
                    this.textBox1.Text = "";//将发送窗口清空
              
            }
            else
            {
                MessageBox.Show("发送内容不能为空");
            }
               
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //server-创建并运行侦听线程
            Thread threadListen = new Thread(new ThreadStart(listen));
            threadListen.Start();
        }

        private void timer1_Tick(object sender, EventArgs e)
        {        
                byte[] receiveBytes = new byte[1024];
                //如果侦听后取得客户端连接,并且客户端的缓冲区中有内容可读,开始接收数据
                if (clientSocket != null)
                {

                    if (clientSocket.Poll(100, SelectMode.SelectRead))
                    {
                        int successReceiveBytes = clientSocket.Receive(receiveBytes);
                        this.textBox2.Text += "客户端:" +"("+ clientSocket.RemoteEndPoint.ToString()+")"+"/r/n" +
                             System.Text.Encoding.UTF8.GetString(receiveBytes, 0, successReceiveBytes) + "/r/n";
                        this.textBox2.SelectionStart = this.textBox2.Text.Length;//使对话窗口的滚动条一直停留在最下方
                        this.textBox2.ScrollToCaret();
                    }

                }
        }
    }
}

客户端代码;
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 ChatToolClient
{
    public partial class Form1 : Form
    {
        Socket clientSocket = null;//客户端套接字
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            try
            {
                //建立与服务器连接的套接字
                IPAddress ip = IPAddress.Parse("172.16.94.134");
                IPEndPoint iep = new IPEndPoint(ip, 82);
                clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                clientSocket.Connect(iep);
                textBox2.Text = "连接成功" + "/r/n";
               
            }
            catch (Exception exp)
            {
                MessageBox.Show(exp.Message);
            }
        }

        private void send_Click(object sender, EventArgs e)
        {

            if (textBox1.Text != "")
            {
                try
                {
                    //发送数据
                    string message = textBox1.Text;
                    byte[] sendbytes = System.Text.Encoding.UTF8.GetBytes(message);
                    int successSendBtyes = clientSocket.Send(sendbytes, sendbytes.Length, SocketFlags.None);
                }
                catch (Exception exp)
                {
                    MessageBox.Show(exp.Message);
                }
                //将发送的数据显示到对话窗口并使对话窗口的滚动条一直停留在最下方
                this.textBox2.Text += "我自己:"+"/r/n"+textBox1.Text + "/r/n";//发完一条消自己息就换行显示
                this.textBox2.SelectionStart = this.textBox2.Text.Length;
                this.textBox2.ScrollToCaret();
                this.textBox1.Text = "";//将发送窗口清空
            }
            else
            {
                MessageBox.Show("发送内容不能为空");
            }
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            byte[] receiveBytes = new byte[1024];
            if (clientSocket.Poll(100, SelectMode.SelectRead))
            {
                int successReceiveBytes = clientSocket.Receive(receiveBytes);
                this.textBox2.Text +="服务器:"+"/r/n"+
                            System.Text.Encoding.UTF8.GetString(receiveBytes, 0, successReceiveBytes) + "/r/n";
                this.textBox2.SelectionStart = this.textBox2.Text.Length;//使对话窗口的滚动条一直停留在最下方
                this.textBox2.ScrollToCaret();
            }     
        }
    }
}

阅读更多
个人分类: Dotnet
想对作者说点什么? 我来说一句

c# socket 实例

2011年05月12日 63KB 下载

socket传输文件实例

2010年08月02日 9KB 下载

vc socket服务端及客户实例

2009年06月19日 7.08MB 下载

C# Socket例子

2007年10月08日 60KB 下载

android socket通讯例子

2011年07月07日 44KB 下载

MFC socket 编程实例

2009年03月29日 36KB 下载

socket实例

2011年12月08日 3KB 下载

没有更多推荐了,返回首页

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭