C# IP/TCP 客户端与服务端

 

1)         流程

2)         服务端程序特点

Ø 一般启动后就一直处于运行状态,以等待客户端进程的请求

Ø 使用的端口往往是熟知端口,便于客户机进程连接请求

Ø 一般拥有较多的系统资源,以便及时响应各个客户机进程的请求

Ø 可以并行处理多个客户机进程的请求,但数目是有一定的限制

Ø 在通信时一般处于被动的一方,不需要知道客户机的IP地址和端口信息

3)         客户端程序特点

Ø 在需要服务端进程的服务时将向服务器进程请求服务,并建立通信连接,得到满足并完成处理后就终止通信连接

Ø 使用向系统申请的临时端口与服务端进程进行通信,通信完成后将释放该端口

Ø 拥有相对较少的系统资源

Ø 在通信时属于主动地一方,需要事先知道服务端的IP地址和端口信息

4)         套接字

套接字可以理解为通信连接的一端,其主要包括协议、主机IP地址和端口号,将两个套接字连接到一起便可以再不同应用进程之间传递数据,因此套接字实现了对网络和传输层协议的封装,为应用进程之间的通信连接的建立、数据传输等通信过程提供了编程界面,使用套接字进行通信示意图为:

5)         工作模型

2.         创建工程

文件à新建à项目

 

在模板中选中控制台应用程序,输入名称后,单击浏览选择保存的位置,单击确定,同样的方法建立好客户端的工程

 

 

 3.         服务端

using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
namespace server
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
               IPAddress Ip = IPAddress.Parse("127.0.0.1");
                //IPAddress提供网际协议地址的类,Parse将IP地址字符串转换为IPAddress的实例
                TcpListener TcpList = new TcpListener(Ip, 8888);
                //TcpListener网络侦听类,从TCP网络客户端侦听连接,TcpListener (参数1,参数2),参数1表示本地IP地址,参数2表示用来侦听传入的端口连接
                TcpList.Start();
                //启动对挂起连接数的传入链接请求的侦听
                Console.WriteLine(“Server start!”);
                Console.WriteLine(“Ip address:” + TcpList.LocalEndpoint);
                //LocalEndpoint获取服务端(即本地)地址与端口等信息
                Console.WriteLine(“Wait”);
                Socket Soc = TcpList.AcceptSocket();
                //AcceptSocket表示接受挂起的连接请求,Socket为套接字接口的类
                Console.WriteLine("Received Connection:" + Soc.RemoteEndPoint);
                //RemoteEndPoint获取客户端地址与端口等信息
                byte[] b = new byte[100];
                int k = Soc.Receive(b);
                //Soc.Receive(b)从socket接收数据,将数据存入接收缓冲区列表中,k的值为该数据的长度
                Console.WriteLine(“Received data from client:”);
                for (int i = 0; i < k; i++)
                    Console.Write(Convert.ToChar(b[i]));
                    //Convert.ToChar(b[i])将数组b转换基本数据类型为char的类型并输出
                ASCIIEncoding AS = new ASCIIEncoding();
                //ASCIIEncoding表示Unicode字符的ASCII字符编码类
                Soc.Send(AS.GetBytes(“Received data!”));
                //Soc.Send向客户端发送数据,AS.GetBytes()获得括号中字符串的bytes值
                Soc.Close();
                //关闭连接并释放所有关联的资源
                TcpList.Stop();
                //关闭侦听
                Console.ReadLine();
                //等待输入,起到暂停的作用
            }
            catch(Exception e)
            {
                Console.WriteLine("Error!" + e.StackTrace);
                //获取当前异常发生时调用堆栈上的帧的字符串
            }
        }
    }
}


 

 4.         客户端

 

using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.IO;
using System.Net.Sockets;
namespace client
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                TcpClient TcpClient = new TcpClient();
                //TcpClient为TCP网络服务提供客户端连接的类
                TcpClient.Connect("127.0.0.1", 8888);
                //Connect方法使用指定的IP地址和端口号将客户端连接到远程TCP主机
                Console.WriteLine("Connect Complete");
                Console.WriteLine("Input string:");
                String str = Console.ReadLine();
                //定义字符串str变量,保存输入的字符
                Stream stm = TcpClient.GetStream();
                //定义数据流,用于发送和接收数据
                ASCIIEncoding AS = new ASCIIEncoding();
                byte[] b = AS.GetBytes(str);
                //将字符串转换为byte类型
                stm.Write(b, 0, b.Length);
                //Write(参数1,参数2,参数3)表示向服务端发送字符串,参数1指将此数组复制到当前流,参数2指从零开始的字节偏移量,参数3指要写入当前流的字节数(即字符串长度)
                Console.WriteLine("Send Complete");
                byte[] bb = new byte[100];
                int k = stm.Read(bb, 0, 100);
                //stm.Read在当前流中读入服务端发来的响应信息,其参数与Write方法参数一致,k值为读入字符串的长度
                for (int i = 0; i < k; i++)
                    Console.Write(Convert.ToChar(bb[i]));
                TcpClient.Close();
                //释放TcpClient实例,并不关闭基础连接
                Console.ReadLine();
            }
            catch (Exception e)
            {
                Console.WriteLine("Error!" + e.StackTrace);
            }
        }
    }
} 

 

 

5.    测试

运行服务端,提示服务端已启动,IP地址为127.0.0.1,使用的端口为8888,等待客户端的连接

运行客户端,提示连接服务端完成,等待输入需发送的信息

客户端运行后,在服务端上出现客户端地址为127.0.0.1,使用的端口为2094

输入信息hello后回车发送,提示发送完成,并收到由服务器发来的确认接收信息

服务器接收到来自客户端发送的hello

 

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是C# Socket通信客户端服务端的例子: 服务端: ```csharp using System; using System.Net; using System.Net.Sockets; using System.Text; public class Server { public static void Main() { byte[] bytes = new byte[1024]; IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName()); IPAddress ipAddress = ipHostInfo.AddressList[0]; IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000); Socket listener = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp); try { listener.Bind(localEndPoint); listener.Listen(10); while (true) { Console.WriteLine("Waiting for a connection..."); Socket handler = listener.Accept(); string data = null; while (true) { bytes = new byte[1024]; int bytesRec = handler.Receive(bytes); data += Encoding.ASCII.GetString(bytes, 0, bytesRec); if (data.IndexOf("<EOF>") > -1) { break; } } Console.WriteLine("Text received : {0}", data); byte[] msg = Encoding.ASCII.GetBytes(data); handler.Send(msg); handler.Shutdown(SocketShutdown.Both); handler.Close(); } } catch (Exception e) { Console.WriteLine(e.ToString()); } Console.WriteLine("\nPress ENTER to continue..."); Console.Read(); } } ``` 客户端: ```csharp using System; using System.Net; using System.Net.Sockets; using System.Text; public class Client { public static void Main() { byte[] bytes = new byte[1024]; try { IPHostEntry ipHostInfo = Dns.GetHostEntry("localhost"); IPAddress ipAddress = ipHostInfo.AddressList[0]; IPEndPoint remoteEP = new IPEndPoint(ipAddress, 11000); Socket sender = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp); try { sender.Connect(remoteEP); Console.WriteLine("Socket connected to {0}", sender.RemoteEndPoint.ToString()); byte[] msg = Encoding.ASCII.GetBytes("This is a test<EOF>"); int bytesSent = sender.Send(msg); int bytesRec = sender.Receive(bytes); Console.WriteLine("Echoed test = {0}", Encoding.ASCII.GetString(bytes, 0, bytesRec)); sender.Shutdown(SocketShutdown.Both); sender.Close(); } catch (ArgumentNullException ane) { Console.WriteLine("ArgumentNullException : {0}", ane.ToString()); } catch (SocketException se) { Console.WriteLine("SocketException : {0}", se.ToString()); } catch (Exception e) { Console.WriteLine("Unexpected exception : {0}", e.ToString()); } } catch (Exception e) { Console.WriteLine(e.ToString()); } Console.WriteLine("\nPress ENTER to continue..."); Console.Read(); } } ``` 这里的例子中,服务端监听本机IP地址和端口11000的连接请求,客户端连接服务端并向服务端发送数据,服务端收到数据并将其原样返回给客户端
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值