教程集 www.jiaochengji.com
教程集 >  脚本编程  >  Asp.net  >  正文 学习C# Socket入门实例代码

学习C# Socket入门实例代码

发布时间:2016-05-09   编辑:jiaochengji.com
本文介绍下,一个简单的C# sockect编程的入门实例,有需要的朋友,参考下吧。

以下代码需要引入命名空间:
 

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

1,Sever服务端代码
 

复制代码 代码示例:

int port = 2000;      //指定端口 (最后些在配置文件中)
String host = "127.0.0.1";   //指定IP
IPAddress ip = IPAddress.Parse(host);//把ip地址字符串转换为IPAddress类型的实例
IPEndPoint ipep = new IPEndPoint(ip, port);//用指定的端口和ip初始化IPEndPoint类的新实例

int recv;//用于表示客户端发送的信息长度
byte[]data=new byte[1024];//用于缓存客户端所发送的信息,通过socket传递的信息必须为字节数组
//IPEndPoint ipep=new IPEndPoint(IPAddress.Any,9050);//本机预使用的IP和端口(本人进行测试没有通过)
Socket newsock=new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);

newsock.Bind(ipep);//绑定
newsock.Listen(10);//监听
Console.WriteLine("waiting for a client");
Socket client=newsock.Accept();//当有可用的客户端连接尝试时执行,并返回一个新的socket,用于与客户端之间的通信
IPEndPoint clientip=(IPEndPoint)client.RemoteEndPoint;
Console.WriteLine("connect with client:"+clientip.Address+"atport:"+clientip.Port);
string welcome="welcome here!";
data=Encoding.ASCII.GetBytes(welcome);
client.Send(data,data.Length,SocketFlags.None);//发送信息
while(true)
{//用死循环来不断的从客户端获取信息
  data=new byte[1024];
  recv=client.Receive(data);
  Console.WriteLine("recv="+recv);
  if(recv==0)//当信息长度为0,说明客户端连接断开
    break;
  Console.WriteLine(Encoding.ASCII.GetString(data,0,recv));
  client.Send(data,recv,SocketFlags.None);
}
Console.WriteLine("Disconnected from"+clientip.Address);
client.Close();
newsock.Close();

2,Client端代码
 

复制代码 代码示例:
byte[] data = new byte[1024];
Socket newclient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
Console.Write("please input the server ip:");
string ipadd = Console.ReadLine();
Console.WriteLine();
Console.Write("please input the server port:");
int port = Convert.ToInt32(Console.ReadLine());
IPEndPoint ie = new IPEndPoint(IPAddress.Parse(ipadd), port);//服务器的IP和端口
try
{
    //因为客户端只是用来向特定的服务器发送信息,所以不需要绑定本机的IP和端口。不需要监听。
    newclient.Connect(ie);
}
catch (SocketException e)
{
    Console.WriteLine("unable to connect to server");
    Console.WriteLine(e.ToString());
    return;
}
int recv = newclient.Receive(data);
string stringdata = Encoding.ASCII.GetString(data, 0, recv);
Console.WriteLine(stringdata);
while (true)
{
    string input = Console.ReadLine();
    if (input == "exit")
        break;
    newclient.Send(Encoding.ASCII.GetBytes(input));
    data = new byte[1024];
    recv = newclient.Receive(data);
    stringdata = Encoding.ASCII.GetString(data, 0, recv);
    Console.WriteLine(stringdata);
}
Console.WriteLine("disconnect from sercer");
newclient.Shutdown(SocketShutdown.Both);
newclient.Close();

有兴趣的朋友,可以动手练习下,看看这段C# socket的代码效果如何?多实践,才会有所提高。

您可能感兴趣的文章:
学习C# Socket入门实例代码
PHP异步调用socket小例子
php为什么不适合socket
Python中的socket网络通信
php socket讲解与实例
如何理解php socket
php socket函数列表
php socket实例之telnet实现的聊天程序
python socket模块是怎么使用?
Java入门笔记9_Socket

[关闭]
~ ~