码迷,mamicode.com
首页 > 其他好文 > 详细

TCP的代码

时间:2016-06-26 16:42:02      阅读:651      评论:0      收藏:0      [点我收藏+]

标签:

 

  视频已经发布,这里是所有的代码仅供参考.

  TCP服务器:

  MainWindow里面的代码:

  1 using System;
  2 using System.Collections.Generic;
  3 using System.Linq;
  4 using System.Text;
  5 using System.Windows;
  6 using System.Windows.Controls;
  7 using System.Windows.Data;
  8 using System.Windows.Documents;
  9 using System.Windows.Input;
 10 using System.Windows.Media;
 11 using System.Windows.Media.Imaging;
 12 using System.Windows.Navigation;
 13 using System.Windows.Shapes;
 14 using System.Net.Sockets;
 15 using System.Net;
 16 using System.IO;
 17 using System.Threading;
 18 
 19 namespace TCPServerExample
 20 {
 21     /// <summary>
 22     /// MainWindow.xaml 的交互逻辑
 23     /// </summary>
 24     public partial class MainWindow : Window
 25     {
 26         TcpListener myListener;
 27         List<User> userList = new List<User>();
 28         bool isExit;
 29         IPAddress ip;
 30         public MainWindow()
 31         {
 32             InitializeComponent();
 33             button1.IsEnabled = true;
 34             button2.IsEnabled = false;
 35         }
 36         //开始按钮
 37         private void button1_Click(object sender, RoutedEventArgs e)
 38         {
 39             button1.IsEnabled = false;
 40             button2.IsEnabled = true;
 41             isExit = true;
 42             //获取本机IP地址
 43             IPAddress[] ips = Dns.GetHostAddresses(Dns.GetHostName());
 44             foreach (var item in ips)
 45             {
 46                 if (item.AddressFamily==AddressFamily.InterNetwork)
 47                 {
 48                     ip = item;
 49                     break;
 50                 }
 51             }
 52 
 53 
 54             myListener = new TcpListener(ip, 51888);
 55             IPEndPoint iep = new IPEndPoint(ip, 51888);
 56             myListener.Start();
 57             //textBlock1.Text += string.Format("服务器在{0}的{1}打开监听",ips[5],port);
 58             textBlock1.Text += string.Format("服务器在{0}打开监听\n", iep);
 59             Thread t1 = new Thread(ListenClientConnect);
 60             t1.Start();
 61         }
 62 
 63         //第一步,开启监听
 64         private void ListenClientConnect()
 65         {
 66             //获取相应客户端套接字
 67             while (isExit)
 68             {
 69                 try
 70                 {
 71                     TcpClient newClient = myListener.AcceptTcpClient();
 72                     User user = new User(newClient);
 73                     userList.Add(user);
 74                     Action act = delegate()
 75                     {
 76                         textBlock1.Text += string.Format("用户{0}连接成功,当前在线用户数为{1}\n",
 77                             newClient.Client.RemoteEndPoint, userList.Count);
 78                     };
 79                     textBlock1.Dispatcher.Invoke(act);
 80                     Thread t2 = new Thread(ReceiveMessage);
 81                     t2.Start(user);
 82                 }
 83                 catch
 84                 {
 85                     break;
 86                 }
 87   
 88             }
 89         }
 90         //第二步,接收消息
 91         private void ReceiveMessage(Object user1)
 92         {
 93             User newuser = (User)user1;
 94             while (isExit)
 95             {
 96                 try
 97                 {
 98                     string message = newuser.br.ReadString();
 99                     AddMessage(string.Format("客户端:{0}发送信息:{1}\n",
100                             newuser.client.Client.RemoteEndPoint, message));
101                    string[] array = message.Split(,);
102                     switch (array[0])
103                     {
104                         case "Login":
105                             {
106                                 newuser.username = array[1];
107                                 //服务器告诉所有在线客户端,有新的用户登录
108                                 for (int i = 0; i < userList.Count; i++)
109                                 {
110                                     if (userList[i].username != newuser.username)
111                                     {
112                                         userList[i].bw.Write("Login," + array[1]);
113                                     }
114                                     newuser.bw.Write("Login," + userList[i].username);
115                                 }
116                                 break;
117                             }
118                         case "Logout":
119                             {
120                                 for (int i = 0; i < userList.Count; i++)
121                                 {
122                                     if (userList[i].username != newuser.username)
123                                     {
124                                         userList[i].bw.Write("Logout," + array[1]);
125                                     }
126                                 }
127                                 userList.Remove(newuser);
128                                 AddMessage("客户端" + newuser.username + "退出," + "当前用户数为:" + userList.Count);
129                                 return;
130                             }
131                         case "Talk":
132                             {
133                                 string target = array[1];
134                                 for (int i = 0; i < userList.Count; i++)
135                                 {
136                                     if (userList[i].username == target)
137                                     {
138                                         userList[i].bw.Write("Talk," + newuser.username + "," + array[2]);
139                                     }
140                                 }
141                                 break;
142                             }
143                         default:
144                             {
145                                 MessageBox.Show("什么意思?");
146                                 break;
147                             }
148                     }
149                 }
150                 catch
151                 {
152                     break;
153                 }
154             }
155         }
156         //第三步,添加消息到textBlock
157         private void AddMessage(string message)
158         {
159             Action act = delegate()
160             {
161                 textBlock1.Text += message;
162             };
163             textBlock1.Dispatcher.Invoke(act);
164         }
165 
166         //结束按钮
167         private void button2_Click(object sender, RoutedEventArgs e)
168         {
169             button1.IsEnabled = true;
170             button2.IsEnabled = false;
171             for (int i = 0; i < userList.Count; i++)
172             {
173                 try
174                 {
175                     userList[i].bw.Write("服务器已停止监听!");
176                 }
177                 catch
178                 {
179                     break;
180                 }
181                 userList[i].Close();
182             }
183             isExit = false;
184             Thread.Sleep(1000);
185             myListener.Stop();
186             
187             for (int i = 0; i < userList.Count; i++)
188             {
189                 userList[i].Close();
190             }
191             textBlock1.Text += "监听结束!";
192         }
193     }
194 }

  User类的代码:

  

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Net.Sockets;
 6 using System.IO;
 7 
 8 namespace TCPServerExample
 9 {
10     class User
11     {
12         public string username{get;set;}
13         public TcpClient client{get;set;}
14         public BinaryWriter bw { get; set; }
15         public BinaryReader br { get; set; }
16         public User(TcpClient newclient)
17         {
18             this.client = newclient;
19             NetworkStream networkstream = newclient.GetStream();
20             bw = new BinaryWriter(networkstream);
21             br = new BinaryReader(networkstream);
22             
23 
24         }
25 
26         public void Close()
27         {
28             client.Close();
29             bw.Close();
30             br.Close();
31 
32         }
33     }
34 }

 

  TCP客户端:

  

  1 using System;
  2 using System.Collections.Generic;
  3 using System.Linq;
  4 using System.Text;
  5 using System.Windows;
  6 using System.Windows.Controls;
  7 using System.Windows.Data;
  8 using System.Windows.Documents;
  9 using System.Windows.Input;
 10 using System.Windows.Media;
 11 using System.Windows.Media.Imaging;
 12 using System.Windows.Navigation;
 13 using System.Windows.Shapes;
 14 using System.Net.Sockets;
 15 using System.Net;
 16 using System.IO;
 17 using System.Threading;
 18 
 19 namespace TCPClientExample
 20 {
 21     /// <summary>
 22     /// MainWindow.xaml 的交互逻辑
 23     /// </summary>
 24     public partial class MainWindow : Window
 25     {
 26         TcpClient newClient;
 27         BinaryWriter bw;
 28         BinaryReader br;
 29         string username;
 30         //enum item { listBox1, textBox1 };
 31         //enum opreation { add,remove};
 32         public MainWindow()
 33         {
 34             InitializeComponent();
 35         }
 36         private void button1_Click(object sender, RoutedEventArgs e)
 37         {
 38             button1.IsEnabled = false;
 39             username = textBox2.Text;
 40             //创建套接字(TcpClient对象)
 41             newClient = new TcpClient();  
 42             //获取服务器IP地址
 43             IPAddress ip = IPAddress.Parse("10.0.2.15");
 44             try
 45             {
 46                 newClient.Connect(ip, 51888);
 47                 listBox1.Items.Add("连接成功!");
 48             }
 49             catch
 50             {
 51                 listBox1.Items.Add("连接失败!");
 52                 button1.IsEnabled = true;
 53                 return;
 54             }
 55             NetworkStream networkStream = newClient.GetStream();
 56             bw = new BinaryWriter(networkStream);
 57             br = new BinaryReader(networkStream);
 58             bw.Write("Login," + username);
 59             Thread t1 = new Thread(ReceiveMessage); 
 60             t1.Start();
 61         }
 62         //第一步,接收消息
 63         private void ReceiveMessage()
 64         {
 65             string message = "";
 66             while (true)
 67             {
 68                 try
 69                 {
 70                     message = br.ReadString();
 71                 }
 72                 catch
 73                 {
 74                     break;
 75                 }
 76                 string[] array = message.Split(,);
 77                 switch (array[0])
 78                 {
 79                     case "Login":
 80                         AddUser(array[1]);
 81                         break;
 82                     case "Logout":
 83                         RemoveUser(array[1]);
 84                         break;
 85                     case "Talk":
 86                         AddMessage(array[1] + ":" + array[2]);
 87                         break;
 88                     default:
 89                         AddMessage(message);
 90                         break;
 91                 }
 92             }
 93         }
 94         //第二步,添加消息到textBlock
 95         private void AddMessage(string message)
 96         {
 97             Action act = delegate()
 98             {
 99                 listBox1.Items.Add(message);
100             };
101             listBox2.Dispatcher.Invoke(act);
102         }
103         //第三步,添加用户到列表
104         private void AddUser(string name)
105         {
106             Action act = delegate()
107             {
108                 listBox2.Items.Add(name);
109             };
110             listBox2.Dispatcher.Invoke(act);
111         }
112         //第四步,移除用户
113         private void RemoveUser(string name)
114         {
115             Action act = delegate()
116             {
117                 listBox2.Items.Remove(name);
118             };
119             listBox2.Dispatcher.Invoke(act);
120         }
121 
122         private void button2_Click(object sender, RoutedEventArgs e)
123         {
124             NetworkStream networkStream = newClient.GetStream();
125              bw = new BinaryWriter(networkStream);
126             string message = textBox1.Text;
127             bw.Write("Talk,"+listBox2.SelectedItem+","+message);
128             listBox1.Items.Add(username + ":" + textBox1.Text);   
129         }
130         private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
131         {
132             try
133             {
134                 bw.Write("Logout," + username);
135             }
136             catch
137             {
138                 MessageBox.Show("与服务器连接失败!");
139             }
140             bw.Close();
141         }
142     }
143 }

 

  我这里的ip都是我自己电脑的ip,你们参考别忘了改ip

 

 

 

  我是蜀云泉,我爱许嵩.吼吼~

  技术分享

 

TCP的代码

标签:

原文地址:http://www.cnblogs.com/yunquan/p/5618016.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!