C# socket编程 异步服务端 同步客户端

异步服务端
using  System;
using  System.Collections.Generic;
using  System.ComponentModel;
using  System.Data;
using  System.Drawing;
using  System.Text;
using  System.Windows.Forms;
using  System.Threading;
using  System.Net;
using  System.Net.Sockets;

namespace  Gps_GateWay
{
    
    
public partial class Form1 : Form
    
{
        
public static ManualResetEvent allDone = new ManualResetEvent(false);
        
private Thread th;
        
private bool listenerRun = true;
        Socket listener;
        
private const int maxsocket = 10;
       
        
public Form1()
        
{
            InitializeComponent();
        }


        
private IPAddress GetLocalIP()
        
{
            IPHostEntry iphostentry 
= Dns.GetHostByName(Dns.GetHostName());
            
return iphostentry.AddressList[0];
        }


        
private void Listen()
        
{
            
try
            
{
                
int port = int.Parse(txtPort.Text);
                IPAddress ipaddress 
= GetLocalIP();
                IPEndPoint ipendpoint 
= new IPEndPoint(ipaddress, port);
                listener 
= new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                listener.Bind(ipendpoint);
                listener.Listen(
50);
                
while (listenerRun)
                
{
                    allDone.Reset();
                    listener.BeginAccept(
new AsyncCallback(AcceptCallBack), listener);
                    allDone.WaitOne();
                }

            }

            
catch (Exception Err)
            
{
                MessageBox.Show(Err.Message);
            }

        }


        
private delegate void GetLstControl(string hostname, string remoteip, string remoteport);

        
private void GetLstStr(string hostname, string remoteip, string remoteport)
        
{
            lstIP.Items.Add(
"[" + hostname + "" + remoteip + ":" + remoteport);
        }



        
private void AcceptCallBack(IAsyncResult ar)
        
{
            
try
            
{
                allDone.Set();
                Socket sok 
= (Socket)ar.AsyncState;
                Socket client 
= sok.EndAccept(ar);
                
                StateObject state 
= new StateObject();
                state.workSocket 
= client;


                EndPoint remoteendpoint 
= client.RemoteEndPoint;
                IPEndPoint ipendpoint 
= (IPEndPoint)remoteendpoint;
                
string remoteip = ipendpoint.Address.ToString();
                
string remoteport = ipendpoint.Port.ToString();

                IPHostEntry iphostentry 
= Dns.GetHostByAddress(ipendpoint.Address);
                
string hostname = iphostentry.HostName;
                GetLstControl getlst 
= new GetLstControl(GetLstStr);
                
this.BeginInvoke(getlst,new object[]{hostname,remoteip,remoteport});

                client.BeginReceive(state.buffer, 
0,StateObject.BufferSize,0new AsyncCallback(ReadCallBack), state);
            }

            
catch (Exception Err)
            
{
               
// MessageBox.Show(Err.Message);
            }

        }


        
private delegate void GetRchControl(string str);

        
private void GetRchMsg(string str)
        
{
            rchMsg.AppendText(str);
        }


        
private void ReadCallBack(IAsyncResult ar)
        
{
            
try
            
{
               
                StateObject state 
= (StateObject)ar.AsyncState;
                Socket hander 
= state.workSocket;

                
                
int readbyte = hander.EndReceive(ar);
                
if (readbyte > 0)
                
{
                    
string strcontent = "";
                    
string str_msg = "";
                    
string strmsg = "";
                    strmsg
=Encoding.BigEndianUnicode.GetString(state.buffer, 0, readbyte);
                    state.sb.Length 
= 0;
                    state.sb.Append(strmsg);
                    strcontent 
= state.sb.ToString() + " ";

                    EndPoint remoteendpoint 
= hander.RemoteEndPoint;
                    IPEndPoint ipendpoint 
= (IPEndPoint)remoteendpoint;
                    
string remoteip = ipendpoint.Address.ToString();
                    
string remoteport = ipendpoint.Port.ToString();

                    IPHostEntry iphostentry 
= Dns.GetHostByAddress(ipendpoint.Address);
                    
string hostname = iphostentry.HostName;

                    
string time = DateTime.Now.ToString();

                    str_msg 
= "(" + time + "" + hostname + "" + strcontent + " ";

                    GetRchControl getrch 
= new GetRchControl(GetRchMsg);
                    
this.BeginInvoke(getrch, new object[] { str_msg });

                    
byte[] byteData = Encoding.BigEndianUnicode.GetBytes("(" + time + "" + "信息发送成功 ");
                    hander.BeginSend(byteData, 
0, byteData.Length, 0new AsyncCallback(SendCallback), hander);
                    hander.BeginReceive(state.buffer, 
0, StateObject.BufferSize, 0new AsyncCallback(ReadCallBack), state);
                    
                }

                
            }

            
catch (Exception Err)
            
{
                MessageBox.Show(Err.Message);
            }

        }


        
private void Send(Socket handler, String data)
        
{
            
byte[] byteData = Encoding.BigEndianUnicode.GetBytes(data);
            handler.BeginSend(byteData, 
0, byteData.Length, 0,new AsyncCallback(SendCallback), handler);
        }


        
private void SendCallback(IAsyncResult ar)
        
{

            
try
            
{

                
//Socket handler = (Socket)ar.AsyncState;
                
//int bytesSent = handler.EndSend(ar);
               
                
//handler.Shutdown(SocketShutdown.Both);

                
//handler.Close();
               
            }

            
catch (Exception Err)
            
{
                MessageBox.Show(Err.Message);
            }

        }


        
private void button1_Click(object sender, EventArgs e)
        
{
            th 
= new Thread(new ThreadStart(Listen)); 
            th.Start();
           
        }

    }


    
public class StateObject
    
{

        
public Socket workSocket = null;

        
public const int BufferSize = 1024;

        
public byte[] buffer = new byte[BufferSize];

        
public StringBuilder sb = new StringBuilder();

    }

}


下载:http://d.download.csdn.net/down/297579/lem12
 同步客户端
using  System;
using  System.Collections.Generic;
using  System.ComponentModel;
using  System.Data;
using  System.Drawing;
using  System.Text;
using  System.Windows.Forms;
using  System.Net;
using  System.Net.Sockets;
using  System.Threading;
namespace  GPs_Client_Test
{
    
public partial class Form1 : Form
    
{
        
private Socket sok;
        
private IPAddress ipaddress;
        
private IPEndPoint ipendpoint;
       
        
public Form1()
        
{
            InitializeComponent();
        }


        
private void button1_Click(object sender, EventArgs e)
        
{
            
try
            
{
                Thread th 
= new Thread(new ThreadStart(Get_TEst));
                th.Start();
            }

            
catch (Exception Err)
            
{
                MessageBox.Show(Err.Message);
            }

        }


        
private void GetStr(string str1)
        
{
            revicestr.AppendText(str1 
+ " ");
        }


        
private delegate void GetControl(string str1);

        
private void Get_TEst()
        
{
            
try
            
{
                ipaddress 
= IPAddress.Parse(textBox1.Text);
                
int port = int.Parse(textBox2.Text);
                ipendpoint 
= new IPEndPoint(ipaddress, port);
                sok 
= new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                sok.Connect(ipendpoint);
               
                
while (true)
                
{
                    
byte[] byt = new byte[1024];
                    
string str = "";
                    sok.Receive(byt, byt.Length, 
0);
                    str 
= Encoding.BigEndianUnicode.GetString(byt);
                    GetControl getcon 
= new GetControl(GetStr);
                    
this.BeginInvoke(getcon, new object[] { str});
                }

            }

            
catch (Exception Err)
            
{
                MessageBox.Show(Err.Message);
            }

        }


        
private void button2_Click(object sender, EventArgs e)
        
{
            
try
            
{
                
byte[] sendbyte = new byte[1024];
                
string str = richTextBox2.Text;
                sendbyte 
= Encoding.BigEndianUnicode.GetBytes(str);
                sok.Send(sendbyte);
            }

            
catch (Exception Err)
            
{
                MessageBox.Show(Err.Message);
            }

        }


        
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        
{
            
try
            
{
                
if (sok != null)
                
{
                    sok.Close();
                }

            }

            
catch (Exception Err)
            
{
            }

        }

    }

}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值