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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值