c#socket同步通信

2015-08-12 19:27:58来源:作者:人点击

c#socket同步通信,有需要的朋友可以参考下。


再次特别感谢张子阳老师的文章,读后深感益处。

废话不多说,先贴代码

这是服务器端代码

using System;using System.Collections.Generic;using System.ComponentModel;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Net;using System.Net.Sockets;using System.Threading;using System.Data.SqlClient;namespace SeverConsole {    class Program {const int bufferSize = 8192;//接受的最大字节数static void Main(string[] args) {Console.WriteLine("Sever is runing");IPAddress ip = new IPAddress( new byte[]{127,0,0,1});TcpListener tcpListener = new TcpListener(ip, 8500);//监听对象tcpListener.Start();while (true) {    try{    TcpClient remoteClient = tcpListener.AcceptTcpClient();//接受客户端的连接请求,会在此处等待。 不会继虚向下执行     Console.WriteLine(@"有客户端连入,{0}<--{1}", remoteClient.Client.LocalEndPoint, remoteClient.Client.RemoteEndPoint);    NetworkStream streamFromClient = remoteClient.GetStream();//获取连接到客户端的流    byte[] buffer = new byte[bufferSize];    int bytesRead = streamFromClient.Read(buffer, 0, bufferSize);//从客户端和服务器获取的流都是二进制形式的    Console.WriteLine("read {0} bytes from client", bytesRead);    string msg = Encoding.Unicode.GetString(buffer, 0, bytesRead);    Console.WriteLine("Received: {0}", msg);    string magSend = msg.ToUpper();    buffer = Encoding.Unicode.GetBytes(magSend);    lock (streamFromClient) {//为了保证数据的完整性以及安全性  锁定数据流streamFromClient.Write(buffer, 0, buffer.Length);Console.WriteLine("send: {0}", msg.ToUpper());    }    }catch(Exception ex){Console.WriteLine(ex.Message);    }    }Console.WriteLine(@"please press 'Q' to exit");//Console.ReadLine();ConsoleKey key;do {    key = Console.ReadKey().Key;} while (key != ConsoleKey.Q);}    }}


这是客户端代码

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Net;using System.Net.Sockets;namespace clientConsole {    class Program {const int bufferSize = 8192;static void Main(string[] args) {Console.WriteLine("Client is running!");TcpClient client;for (int i = 0; i < 4; i++) {     client = new TcpClient();try {client.Connect("127.0.0.1", 8500);    } catch (Exception ex) {Console.WriteLine(ex.Message);    }    Console.WriteLine("connecting successful");    Console.WriteLine("{0}-->{1}", client.Client.LocalEndPoint, client.Client.RemoteEndPoint);    string msg = "let me to connect with you ";    NetworkStream clientToSever = client.GetStream();    byte[] buffer = Encoding.Unicode.GetBytes(msg);    clientToSever.Write(buffer, 0, buffer.Length);    int t = buffer.Length;    Console.WriteLine("Send: {0}", msg);    lock (clientToSever) {//int bytesRead = clientToSever.Read(buffer, 0, t);msg = Encoding.Unicode.GetString(buffer, 0, buffer.Length);Console.WriteLine("Received: {0}", msg);    }}ConsoleKey key;do {    key = Console.ReadKey().Key;} while (key != ConsoleKey.Q);}    }}


转载请说明出处

版权声明:本文为博主原创文章,未经博主允许不得转载。

微信扫一扫

第七城市微信公众平台