面向连接的套接字

在服务器能够向客户机传输数据之前,必须做以下四件事:

1、创建一个套接字

2、将所创建的套接字与本地IPEndPoint绑定

3、设置套接字为收听模式

4、在套接字上接收接入的连接 

创建一个简单的TCP服务器:

 

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

namespace SimpleTcpSrvr1
{
    
class Program
    
{
        
static void Main(string[] args)
        
{
            
int recv;
            
byte[] data = new byte[1024];
            IPEndPoint ipep 
= new IPEndPoint(IPAddress.Any, 9050);
            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();
            IPEndPoint clientep 
= (IPEndPoint)client.RemoteEndPoint;
            Console.WriteLine(
"Connected with {0} at port {1}", clientep.Address, clientep.Port);
            
string welcome = "Welcome to my test sever";
            data 
= Encoding.ASCII.GetBytes(welcome);
            client.Send(data, data.Length, SocketFlags.None);
            
while (true)
            
{
                data 
= new byte[1024];
                recv 
=client.Receive(data);
                
if (recv == 0)
                    
break;
                Console.WriteLine(Encoding.ASCII.GetString(data, 
0, recv));
                client.Send(data, recv, SocketFlags.None);
            }

            Console.WriteLine(
"Disconnected from {0}", clientep.Address);
            client.Close();
            newsock.Close();
            Console.Read();
        }

    }

}

 

这个程序中没有任何修饰或技巧。首先,定义一个空字节数组作为数据缓冲器,用于缓存流入和流出的消息。不论传输什么类型的数据Socket Receive()和Send()只能使用字节数组,所有通过这个Socket传输的数据必须转换为字节数组。

接下来为本地服务器定义IPEndPoint对象:IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 9050);

接下来调用Socket()构造函数创建TCP套接字,然后使用Bind()和Listen()将该套接字与新IPEndPoint对象进行绑定,并收听接入连接。

最后,使用Accept()方法接收来自客户机的接入连接尝试,Accept()返回一个Socket对象在与客户机的所有通信中必须使用这个新的Socket对象。

用命令  telnet 127.0.0.1 9050 测试服务器。

简单的客户机程序

 

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

namespace SimpleTcpClient
{
    
class Program
    
{
        
static void Main(string[] args)
        
{
            
byte[] data = new byte[1024];
            
string input, stringData;
            IPEndPoint ipep 
= new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9050);
            Socket server 
= new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            
try
            
{
                server.Connect(ipep);
            }

            
catch(SocketException e)
            
{
                Console.WriteLine(
"Unable to connect to server");
                Console.WriteLine(e.ToString());
                Console.ReadLine();
                
return;
            }

            
int recv = server.Receive(data);
            stringData 
= Encoding.ASCII.GetString(data,0,recv);
            Console.WriteLine(stringData);
            
while (true)
            
{
                input 
= Console.ReadLine();
                
if (input == "exit")
                    
break;
                server.Send(Encoding.ASCII.GetBytes(input));
                data 
= new byte[1024];
                recv 
= server.Receive(data);
                stringData 
= Encoding.ASCII.GetString(data, 0, recv);
                Console.WriteLine(stringData);
            }

            Console.WriteLine(
"Disconnecting from server...");
            server.Shutdown(SocketShutdown.Both);
            server.Close();
        }

    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值