标签:style blog http color io os ar for sp
整理一份Socket代码,整理前辈的代码
http://www.cnblogs.com/yellowapplemylove/archive/2011/04/19/2021586.html
直接贴代码
一、客户端
1 /// <summary> 2 /// Client客户端 3 /// </summary> 4 public partial class ClientForm : Form 5 { 6 private IPAddress serverIp ; 7 private IPEndPoint serverFullAddr; 8 private Socket sock; 9 public ClientForm() 10 { 11 InitializeComponent(); 12 this.Load += (e, v) => 13 { 14 txtIP.Text = "127.0.0.1"; 15 txtPort.Text = "2014"; 16 }; 17 } 18 private void btnConnect_Click(object sender, EventArgs e) 19 { 20 try 21 { 22 serverIp = IPAddress.Parse(txtIP.Text.Trim()); 23 serverFullAddr = new IPEndPoint(serverIp, int.Parse(txtPort.Text.Trim())); 24 sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); 25 sock.Connect(serverFullAddr);//建立与远程主机的连接 26 //启动新线程用于接收数据 27 Thread t = new Thread(new ThreadStart(ReceiveMsg)); 28 t.Name = "接收消息"; 29 //一个线程或者是后台线程或者是前台线程。后台线程与前台线程类似,区别是后台线程不会防止进程终止。 30 //一旦属于某一进程的所有前台线程都终止,公共语言运行库就会通过对任何仍然处于活动状态的后台线程调用 abort 来结束该进程。 31 t.IsBackground = true; 32 t.Start(); 33 } 34 catch(Exception ex) 35 { 36 MessageBox.Show(ex.Message); 37 } 38 } 39 private void ReceiveMsg() 40 { 41 try 42 { 43 while (true) 44 { 45 byte[] byterec = new byte[100]; 46 this.sock.Receive(byterec); 47 string strrec = System.Text.Encoding.UTF8.GetString(byterec); 48 if (this.txtReceive.InvokeRequired) 49 { 50 this.txtReceive.Invoke(new EventHandler(ChangerText), new object[] { strrec, EventArgs.Empty }); 51 } 52 } 53 } 54 catch (Exception ex) 55 { 56 MessageBox.Show("接收服务器消息发生错误" + ex.Message); 57 } 58 } 59 private void ChangerText(object obj, EventArgs e) 60 { 61 string s = Convert.ToString(obj); 62 this.txtReceive.AppendText(s + Environment.NewLine); 63 } 64 private void btnSend_Click(object sender, EventArgs e) 65 { 66 byte[] byteSend =System.Text.Encoding.UTF8.GetBytes(this.txtSend.Text.ToCharArray()); 67 try 68 { 69 sock.Send(byteSend); 70 } 71 catch 72 { 73 MessageBox.Show("向服务器发送数据错误"); 74 } 75 } 76 private void btnClose_Click(object sender, EventArgs e) 77 { 78 try 79 { 80 this.sock.Shutdown(SocketShutdown.Receive); 81 this.sock.Close(); 82 Application.Exit(); 83 } 84 catch 85 { 86 MessageBox.Show("关闭连接发生错误"); 87 } 88 } 89 }
二、服务器端
1 public partial class ServerForm : Form 2 { 3 private IPAddress serverIp ;//IP地址 4 private IPEndPoint serverFullAddr;//完整终端地址 5 private Socket sock; 6 private System.Timers.Timer timer; 7 private ArrayList allStocksList;//当建立了多个连接时用于保存连接 8 public ServerForm() 9 { 10 InitializeComponent(); 11 this.Load += (e, v) => 12 { 13 txtIP.Text = "127.0.0.1"; 14 txtPort.Text = "2014"; 15 }; 16 } 17 private void btstart_click(object sender, EventArgs e) 18 { 19 serverIp = IPAddress.Parse(txtIP.Text.Trim()); 20 serverFullAddr = new IPEndPoint(serverIp, int.Parse(txtPort.Text.Trim())); 21 //构造socket对象,套接字类型为“流套接字”,指定五元组中的协议元 22 sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream,ProtocolType.Tcp); 23 //指定五元组中的本地二元,即本地主机地址和端口号 24 sock.Bind(serverFullAddr); 25 //监听是否有连接传入,指定挂起的连接队列的最大值为20 26 sock.Listen(20); 27 allStocksList = new ArrayList(); 28 //构造定时器,时间间隙为1秒,即每隔一秒执行一次accept()方法,以获取连接请求队列中//第一个挂起的连接请求 29 timer = new System.Timers.Timer(1000); 30 timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed); 31 timer.Enabled = true; 32 } 33 private void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) 34 { 35 timer.Enabled = false; 36 //执行accept(),当挂起队列为空时将阻塞本线程,同时由于上一语句,定时器将停止,直//至有连接传入 37 Socket acceptSTock = sock.Accept(); 38 //将accept()产生的socket对象存入arraylist 39 allStocksList.Add(acceptSTock); 40 // 构造threading.timer对象,这将导致程序另启线程。线程将执行回调函数,该委托限制//函数参数须为object型。 41 //threading.timer构造器的第二个参数即传入回调函数的参数;第//三个参数指定调用回调函数之前的延时,取0则立即启动; 42 //最后一个参数指定调用回调函数//的时间间隔,取0则只执行一次。 43 System.Threading.Timer ti = new System.Threading.Timer(new TimerCallback(receivemsg), acceptSTock, 0, 0); 44 timer.Enabled = true; 45 } 46 47 private void receivemsg(object obj) 48 { 49 Socket acceptStock = (Socket)obj; 50 try 51 { 52 while (true) 53 { 54 byte[] byteArray = new byte[100]; 55 acceptStock.Receive(byteArray);//接收数据 56 //将字节数组转成字符串 57 string strrec = System.Text.Encoding.UTF8.GetString(byteArray); 58 if (this.txtReceive.InvokeRequired) 59 { 60 this.txtReceive.Invoke(new EventHandler(this.ChangerText), new object[] { strrec, EventArgs.Empty }); 61 } 62 } 63 } 64 catch (Exception ex) 65 { 66 acceptStock.Close(); 67 MessageBox.Show("接收客户端消息错误" + ex.Message); 68 } 69 } 70 private void ChangerText(object obj, EventArgs e) 71 { 72 string s = Convert.ToString(obj); 73 this.txtReceive.AppendText(s + Environment.NewLine); 74 } 75 private void btnSend_Click(object sender, EventArgs e) 76 { 77 Socket sc = null; 78 byte[] byteSend =System.Text.Encoding.UTF8.GetBytes(this.tbsend.Text.ToCharArray()); 79 try 80 { 81 //向所有的客户端发送数据 82 for (int i = 0; i < allStocksList.Count; i++) 83 { 84 sc = allStocksList[i] as Socket; 85 sc.Send(byteSend); 86 } 87 } 88 catch (Exception ex) 89 { 90 if (sc != null) 91 { 92 sc.Close(); 93 } 94 95 MessageBox.Show("向客户端发送信息错误" + ex.Message); 96 } 97 } 98 99 private void btnClose_Click(object sender, EventArgs e) 100 { 101 try 102 { 103 Application.Exit(); 104 } 105 catch (Exception ex) 106 { 107 MessageBox.Show("关闭连接发生错误" + ex.Message); 108 } 109 } 110 }
标签:style blog http color io os ar for sp
原文地址:http://www.cnblogs.com/OnlyVersion/p/4024722.html