C# Socket编程

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;

namespace SocketTest
{
    class Program
    {
        static void Main(string[] args)
        {
            int length;
            byte[] bytes = new byte[1024];
            //创建一个Socket对象
            Socket socketSend = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            //将本机IP地址和端口与套接字绑定,为接受做准备
            IPEndPoint myHost = new IPEndPoint(IPAddress.Any, 8000);
            socketSend.Bind(myHost);//绑定本机
            //定义远程IP地址和端口,为发送数据做准备
            IPEndPoint remote = new IPEndPoint(IPAddress.Parse("192.168.1.101"), 8000);
            EndPoint remoteHost = (EndPoint)remote;//从IPEndPoint得到EndPoint类型
            Console.Write("输入发送的信息:");
            string str = Console.ReadLine();
            bytes = System.Text.Encoding.Unicode.GetBytes(str);//字符串转换为字节数组
            //向远程中断发送信息
            socketSend.SendTo(bytes, bytes.Length, SocketFlags.None, remoteHost);
            while (true)
            {
                Console.WriteLine("等待接受...");
                //从本地绑定的IP地址和端口接受远程终端的数据,返回接受的字节数
                length = socketSend.ReceiveFrom(bytes, ref remoteHost);
                Console.WriteLine("等待接受消息:{0}", str);
                if (str=="Q") //如果接受到的是Q,则跳出循环
                {
                    break;
                }
                Console.Write("输入会送消息(Q 退出):");
                str = Console.ReadLine();//获取用户信息
                bytes = System.Text.Encoding.Unicode.GetBytes(str);//将字符串转化成字节数组
                socketSend.SendTo(bytes, bytes.Length, SocketFlags.None, remoteHost);
            }
            socketSend.Close();//关闭套接字
            Console.Write("对方已经推出了,请按回车结束");
            Console.ReadLine();
        }
       
    }
}

posted @ 2012-10-13 16:58  蓬莱仙羽  阅读(167)  评论(0编辑  收藏  举报