C#如何实现套接字发送接收数据
C#如何实现套接字发送接收数据
这篇文章主要介绍了C#如何实现套接字发送接收数据,具有一定借鉴价值,感兴趣的朋友可以参考下,希望大家阅读完这篇文章之后大有收获,下面让小编带着大家一起了解一下。
具体内容如下
服务端
namespaceTestServer{publicpartialclassServerForm:Form{SocketsocketSend;//将远程连接的客户端的IP地址和socket存入集合Dictionary<string,Socket>dicSocket=newDictionary<string,Socket>();publicServerForm(){InitializeComponent();}privatevoidbtnStart_Click(objectsender,EventArgse){try{//当点击开始监听后,在服务器创建一个负责监听IP地址和端口号的socketSocketsocketWatch=newSocket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);IPAddressip=IPAddress.Any;//;IPAddress.Parse(txtServer.Text)IPEndPointpoint=newIPEndPoint(ip,Convert.ToInt32(txtPort.Text));//监听socketWatch.Bind(point);ShowMsg("监听成功");socketWatch.Listen(10);Threadth=newThread(Listen);th.IsBackground=true;th.Start(socketWatch);}catch{}}voidListen(objecto){//等待客户端连接并创建一个负责通信的SocketSocketsocketWatch=oasSocket;while(true){socketSend=socketWatch.Accept();dicSocket.Add(socketSend.RemoteEndPoint.ToString(),socketSend);cboUsers.Items.Add(socketSend.RemoteEndPoint.ToString());ShowMsg(socketSend.RemoteEndPoint.ToString()+":"+"连接成功");Threadth=newThread(Recive);th.IsBackground=true;th.Start(socketSend);}}voidRecive(objecto){socketSend=oasSocket;while(true){//客户端连接成功后,服务器应接受客户端发来的消息byte[]buffer=newbyte[1024*1024*2];//实际接收到的有效字节数intr=socketSend.Receive(buffer);if(r==0){break;}stringstr=Encoding.UTF8.GetString(buffer,0,r);ShowMsg(socketSend.RemoteEndPoint+":"+str);}}voidShowMsg(stringstr){txtLog.AppendText(str+"\r\n");}privatevoidForm1_Load(objectsender,EventArgse){Control.CheckForIllegalCrossThreadCalls=false;}privatevoidbtnSend_Click(objectsender,EventArgse){stringstr=txtMsg.Text;byte[]buffer=Encoding.UTF8.GetBytes(str);stringip=cboUsers.SelectedItem.ToString();dicSocket[ip].Send(buffer);//socketSend.Send(buffer);txtMsg.Text="";}privatevoidbtnSendUser_Click(objectsender,EventArgse){stringjson=JsonConvert.SerializeObject(UserList());byte[]buffer=Encoding.UTF8.GetBytes(json);socketSend.Send(buffer);}privateList<User>UserList(){List<User>userList=newList<User>();Useruser=null;stringsql="select*fromuser_table";SqlCommandcmd=SqlUtils.ConnectSql(sql);SqlDataReadersdr=cmd.ExecuteReader();while(sdr.Read()){user=newUser(sdr.GetInt32(0),sdr.GetString(1),sdr.GetString(2),sdr.GetInt32(3));userList.Add(user);}returnuserList;}}}
客户端
namespaceTestClient{publicpartialclassClientForm:Form{SocketsocketSend;publicClientForm(){InitializeComponent();}privatevoidbtnStart_Click(objectsender,EventArgse){try{//创建负责通信的socketsocketSend=newSocket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);IPAddressip=IPAddress.Parse(txtServer.Text);IPEndPointpoint=newIPEndPoint(ip,Convert.ToInt32(txtPort.Text));socketSend.Connect(point);ShowMsg("连接成功");Threadth=newThread(Recive);th.IsBackground=true;th.Start();}catch{}}voidRecive(){while(true){//客户端连接成功后,服务器应接受客户端发来的消息byte[]buffer=newbyte[1024*1024*2];//实际接收到的有效字节数intr=socketSend.Receive(buffer);if(r==0){break;}stringstr=Encoding.UTF8.GetString(buffer,0,r);ShowMsg(socketSend.RemoteEndPoint+":"+str);}}voidShowMsg(stringstr){txtLog.AppendText(str+"\r\n");}privatevoidForm1_Load(objectsender,EventArgse){Control.CheckForIllegalCrossThreadCalls=false;}privatevoidbtnSend_Click(objectsender,EventArgse){stringstr=txtMsg.Text.Trim();byte[]buffer=Encoding.UTF8.GetBytes(str);socketSend.Send(buffer);txtMsg.Text="";}}}
效果
发送json数据
感谢你能够认真阅读完这篇文章,希望小编分享的“C#如何实现套接字发送接收数据”这篇文章对大家有帮助,同时也希望大家多多支持恰卡编程网,关注恰卡编程网行业资讯频道,更多相关知识等着你来学习!