网上找到最好关于socket编程实例源码

在博客园看到关于socket最简单最精辟最好的实例源代码!

TCPServerCode
 1 using System;
2 using System.Net;
3 using System.Net.Sockets;
4 using System.Text;
5
6 namespace tcpserver
7 {
8 /// <summary>
9 /// Class1 的摘要说明。
10 /// </summary>
11 class server
12 {
13 /// <summary>
14 /// 应用程序的主入口点。
15 /// </summary>
16 [STAThread]
17 static void Main(string[] args)
18 {
19 //
20 // TODO: 在此处添加代码以启动应用程序
21 //
22 int recv;//用于表示客户端发送的信息长度
23 byte[] data=new byte[1024];//用于缓存客户端所发送的信息,通过socket传递的信息必须为字节数组
24 IPEndPoint ipep=new IPEndPoint(IPAddress.Any,9050);//本机预使用的IP和端口
25 Socket newsock=new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
26 newsock.Bind(ipep);//绑定
27 newsock.Listen(10);//监听
28 Console.WriteLine("waiting for a client");
29 Socket client=newsock.Accept();//当有可用的客户端连接尝试时执行,并返回一个新的socket,用于与客户端之间的通信
30 IPEndPoint clientip=(IPEndPoint)client.RemoteEndPoint;
31 Console.WriteLine("connect with client:"+clientip.Address+" at port:"+clientip.Port);
32 string welcome="welcome here!";
33 data=Encoding.ASCII.GetBytes(welcome);
34 client.Send(data,data.Length,SocketFlags.None);//发送信息
35 while(true)
36 {//用死循环来不断的从客户端获取信息
37 data=new byte[1024];
38 recv=client.Receive(data);
39 Console.WriteLine("recv="+recv);
40 if (recv==0)//当信息长度为0,说明客户端连接断开
41 break;
42 Console.WriteLine(Encoding.ASCII.GetString(data,0,recv));
43 client.Send(data,recv,SocketFlags.None);
44 }
45 Console.WriteLine("Disconnected from"+clientip.Address);
46 client.Close();
47 newsock.Close();
48
49 }
50 }
51 }
TCPClient
 1 using System;
2 using System.Net;
3 using System.Net.Sockets;
4 using System.Text;
5
6 namespace tcpclient
7 {
8 /// <summary>
9 /// Class1 的摘要说明。
10 /// </summary>
11 class client
12 {
13 /// <summary>
14 /// 应用程序的主入口点。
15 /// </summary>
16 [STAThread]
17 static void Main(string[] args)
18 {
19 //
20 // TODO: 在此处添加代码以启动应用程序
21 //
22 byte[] data=new byte[1024];
23 Socket newclient=new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
24 Console.Write("please input the server ip:");
25 string ipadd=Console.ReadLine();
26 Console.WriteLine();
27 Console.Write("please input the server port:");
28 int port=Convert.ToInt32(Console.ReadLine());
29 IPEndPoint ie=new IPEndPoint(IPAddress.Parse(ipadd),port);//服务器的IP和端口
30 try
31 {
32 //因为客户端只是用来向特定的服务器发送信息,所以不需要绑定本机的IP和端口。不需要监听。
33 newclient.Connect(ie);
34 }
35 catch(SocketException e)
36 {
37 Console.WriteLine("unable to connect to server");
38 Console.WriteLine(e.ToString());
39 return;
40 }
41 int recv = newclient.Receive(data);
42 string stringdata=Encoding.ASCII.GetString(data,0,recv);
43 Console.WriteLine(stringdata);
44 while(true)
45 {
46 string input=Console.ReadLine();
47 if(input=="exit")
48 break;
49 newclient.Send(Encoding.ASCII.GetBytes(input));
50 data=new byte[1024];
51 recv=newclient.Receive(data);
52 stringdata=Encoding.ASCII.GetString(data,0,recv);
53 Console.WriteLine(stringdata);
54 }
55 Console.WriteLine("disconnect from sercer");
56 newclient.Shutdown(SocketShutdown.Both);
57 newclient.Close();
58
59 }
60 }
61 }
UDPServer
 1 using System;
2 using System.Collections.Generic;
3 using System.Text;
4 using System.Net;
5 using System.Net.Sockets;
6 namespace SimpleUdpSrvr
7 {
8 class Program
9 {
10 static void Main(string[] args)
11 {
12 int recv;
13 byte[] data = new byte[1024];
14 IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 9050);//定义一网络端点
15 Socket newsock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);//定义一个Socket
16 newsock.Bind(ipep);//Socket与本地的一个终结点相关联
17 Console.WriteLine("Waiting for a client..");
18
19 IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);//定义要发送的计算机的地址
20 EndPoint Remote = (EndPoint)(sender);//
21 recv = newsock.ReceiveFrom(data, ref Remote);//接受数据
22 Console.WriteLine("Message received from{0}:", Remote.ToString());
23 Console.WriteLine(Encoding.ASCII.GetBytes(data,0,recv));
24
25 string welcome = "Welcome to my test server!";
26 data = Encoding.ASCII.GetBytes(welcome);
27 newsock.SendTo(data, data.Length, SocketFlags.None, Remote);
28 while (true)
29 {
30 data = new byte[1024];
31 recv = newsock.ReceiveFrom(data, ref Remote);
32 Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv));
33 newsock.SendTo(data, recv, SocketFlags.None, Remote);
34 }
35 }
36 }
37 }
UDPServer
 1 using System;
2 using System.Collections.Generic;
3 using System.Text;
4 using System.Net;
5 using System.Net.Sockets;
6 namespace SimpleUdpSrvr
7 {
8 class Program
9 {
10 static void Main(string[] args)
11 {
12 int recv;
13 byte[] data = new byte[1024];
14 IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 9050);//定义一网络端点
15 Socket newsock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);//定义一个Socket
16 newsock.Bind(ipep);//Socket与本地的一个终结点相关联
17 Console.WriteLine("Waiting for a client..");
18
19 IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);//定义要发送的计算机的地址
20 EndPoint Remote = (EndPoint)(sender);//
21 recv = newsock.ReceiveFrom(data, ref Remote);//接受数据
22 Console.WriteLine("Message received from{0}:", Remote.ToString());
23 Console.WriteLine(Encoding.ASCII.GetBytes(data,0,recv));
24
25 string welcome = "Welcome to my test server!";
26 data = Encoding.ASCII.GetBytes(welcome);
27 newsock.SendTo(data, data.Length, SocketFlags.None, Remote);
28 while (true)
29 {
30 data = new byte[1024];
31 recv = newsock.ReceiveFrom(data, ref Remote);
32 Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv));
33 newsock.SendTo(data, recv, SocketFlags.None, Remote);
34 }
35 }
36 }
37 }
UDPClient
 1 using System;
2 using System.Collections.Generic;
3 using System.Text;
4 using System.Net;
5 using System.Net.Sockets;
6 namespace SimpleUdpClient
7 {
8 class Program
9 {
10 static void Main(string[] args)
11 {
12 byte[] data = new byte[1024];//定义一个数组用来做数据的缓冲区
13 string input, stringData;
14 IPEndPoint ipep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9050);
15 Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
16 string welcome = "Hello,are you there?";
17 data = Encoding.ASCII.GetBytes(welcome);
18 server.SendTo(data, data.Length, SocketFlags.None, ipep);//将数据发送到指定的终结点
19
20 IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
21 EndPoint Remote = (EndPoint)sender;
22 data = new byte[1024];
23 int recv = server.ReceiveFrom(data, ref Remote);//接受来自服务器的数据
24
25 Console.WriteLine("Message received from{0}:", Remote.ToString());
26 Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv));
27 while (true)//读取数据
28 {
29 input = Console.ReadLine();//从键盘读取数据
30 if (input == "text")//结束标记
31 {
32 break;
33 }
34 server.SendTo(Encoding.ASCII.GetBytes(input), Remote);//将数据发送到指定的终结点Remote
35 data = new byte[1024];
36 recv = server.ReceiveFrom(data, ref Remote);//从Remote接受数据
37 stringData = Encoding.ASCII.GetString(data, 0, recv);
38 Console.WriteLine(stringData);
39 }
40 Console.WriteLine("Stopping client");
41 server.Close();
42 }
43 }
44 }
posted @ 2011-08-03 18:38  JaysD  阅读(279)  评论(0编辑  收藏  举报