服務(wù)端 using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading.Tasks; namespace tSocket { class Program { byte[] bytes = new byte[1024]; Socket cSocket; static void Main(string[] args) { Program p = new Program(); //打開鏈接 p.open(); //向服務(wù)端發(fā)送消息 Console.WriteLine("請(qǐng)輸入你要對(duì)服務(wù)端發(fā)送的消息:"); string mes = Console.ReadLine(); string con = p.messge(mes); Console.WriteLine("接受到服務(wù)端的消息:" + con); } byte[] data = new byte[1024]; string messge(string mes) { //將發(fā)送的消息轉(zhuǎn)成字節(jié)數(shù)組 bytes = Encoding.UTF8.GetBytes(mes); //發(fā)送 cSocket.Send(bytes); while (true) { //接受服務(wù)端發(fā)送的消息,放入字節(jié)數(shù)組 int len = cSocket.Receive(data); //將字節(jié)數(shù)組轉(zhuǎn)成可讀明文 string con = Encoding.UTF8.GetString(data, 0, len); ////返回 return con; } } /// <summary> /// 打開鏈接 /// </summary> void open() { //創(chuàng)建Socket對(duì)象 指定連接方式 cSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //創(chuàng)建IP,端口 IPAddress ip = IPAddress.Parse("10.116.253.10"); int port = 7526; //封裝IP和端口 IPEndPoint Ipoint = new IPEndPoint(ip, port); //打開鏈接 cSocket.Connect(Ipoint); } } } 客戶端 using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading.Tasks; namespace ServerSocket { class Program { static void Main(string[] args) { //創(chuàng)建Socket對(duì)象,指定他的鏈接方式 Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //建立IP string ip = "10.116.253.10"; //創(chuàng)建端口 int prot = 7526;//1~9999 IPAddress IPAdd = IPAddress.Parse(ip); //封裝IP和端口 IPEndPoint point = new IPEndPoint(IPAdd, prot); //綁定IP和端口 serverSocket.Bind(point); //開始監(jiān)聽 serverSocket.Listen(100); Console.WriteLine("開始監(jiān)聽!"); int i = 0; while (true) { i++; //接受客戶鏈接 Socket cSocket = serverSocket.Accept(); Console.WriteLine("接受第"+i+"個(gè)客戶的連接!"); Client c = new Client(cSocket); } } } } using System; using System.Collections.Generic; using System.Linq; using System.Net.Sockets; using System.Text; using System.Threading; using System.Threading.Tasks; namespace ServerSocket { class Client { Socket sSocket; byte[] data = new byte[1024]; Thread t; public Client(Socket cSocket) { //接受客戶的連接 sSocket = cSocket; //創(chuàng)建線程 t = new Thread(Mess); //開始線程 t.Start(); } void Mess() { try { while (true) { //將用戶發(fā)送的數(shù)據(jù)以一個(gè)字節(jié)數(shù)組裝起 int length = sSocket.Receive(data); Console.WriteLine("接受客戶端發(fā)的消息!"); string mess = Encoding.UTF8.GetString(data, 0, length); if (mess == "con") { string con = "DataSource =."; byte[] bytes = Encoding.UTF8.GetBytes(con); sSocket.Send(bytes); } Console.WriteLine("接到用戶的消息:" + mess); } } catch (Exception) { sSocket.Close(); } } } } |
|