Csharp/C#教程:C#.Net中的TCP / IP客户端套接字程序使用IP地址和端口号分享


C#.Net中的TCP / IP客户端套接字程序使用IP地址和端口号

TCP / IP客户端套接字程序。 这里我的主要要求是客户端发送消息和服务器接收消息并存储在C#.Net的数据库表中,使用服务器IP地址和端口号。

您正在谈论一个简单的服务器 – 客户端程序。

你需要做什么。

指南:

更新 – 根据要求和指导,这是一个工作的客户端和服务器

客户-

using System; using System.Text; using System.Net; using System.Net.Sockets; using System.IO; namespace socket_prog { class Client { private static void Main(String[] args) { byte[] data = new byte[10]; IPHostEntry iphostInfo = Dns.GetHostEntry(Dns.GetHostName()); IPAddress ipAdress = iphostInfo.AddressList[0]; IPEndPoint ipEndpoint = new IPEndPoint(ipAdress, 32000); Socket client = new Socket(ipAdress.AddressFamily, SocketType.Stream, ProtocolType.Tcp); try { client.Connect(ipEndpoint); Console.WriteLine("Socket created to {0}", client.RemoteEndPoint.ToString()); byte[] sendmsg = Encoding.ASCII.GetBytes("This is from Clientn"); int n = client.Send(sendmsg); int m = client.Receive(data); Console.WriteLine("" + Encoding.ASCII.GetString(data)); client.Shutdown(SocketShutdown.Both); client.Close(); } catch (Exception e) { Console.WriteLine(e.ToString()); } Console.WriteLine("Transmission end."); Console.ReadKey(); } } } 

服务器-

 using System; using System.Text; using System.Net; using System.Net.Sockets; using System.IO; namespace socket_prog { class Server { static void Main(string[] args) { byte[] buffer = new byte[1000]; byte[] msg = Encoding.ASCII.GetBytes("From servern"); string data = null; IPHostEntry iphostInfo = Dns.GetHostEntry(Dns.GetHostName()); IPAddress ipAddress = iphostInfo.AddressList[0]; IPEndPoint localEndpoint = new IPEndPoint(ipAddress, 32000); ConsoleKeyInfo key; int count = 0; Socket sock = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp); sock.Bind(localEndpoint); sock.Listen(5); while (true) { Console.WriteLine("nWaiting for clients..{0}", count); Socket confd = sock.Accept(); int b = confd.Receive(buffer); data += Encoding.ASCII.GetString(buffer, 0, b); Console.WriteLine("" + data); data = null; confd.Send(msg); Console.WriteLine("n<< Continue 'y' , Exit 'e'>>"); key = Console.ReadKey(); if (key.KeyChar == 'e') { Console.WriteLine("nExiting..Handled {0} clients", count); confd.Close(); System.Threading.Thread.Sleep(5000); break; } confd.Close(); count++; } } } } 

先运行服务器。 然后运行客户端。

上述就是C#学习教程:C#.Net中的TCP / IP客户端套接字程序使用IP地址和端口号分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/1019109.html

(0)
上一篇 2022年1月4日
下一篇 2022年1月4日

精彩推荐