Tcp通信 暑期学习笔记(二)
一直想学习网络编程,好不容易终于写出来了。非常感谢 李.net,他的文章最终帮助了我。学习中总是有那么多曲折。
因为我用的是vista,默认支持ipv6,给我带来很大痛苦。希望我下面的代码能给我跟我一样的初学者一点帮助。
Code
1 using System;
2 using System.Collections.Generic;
3 using System.ComponentModel;
4 using System.Data;
5 using System.Drawing;
6 using System.Text;
7 using System.Windows.Forms;
8 using System.Threading;
9 using System.Net;
10 using System.Net.Sockets;
11
12 namespace NetStudy
13 {
14 delegate void ListBoxAppendItem(object o);
15 public partial class MyTalk : Form
16 {
17
18 #region Vars
19 IPAddress targetIP;
20
21 Thread serverThread, clientThread,receiveThread;
22 Socket serverSocket, clientSocket,receiveSocket;
23
24 ListBoxAppendItem AddItem ;
25 void addItem(object o)
26 {
27 listBox.Items.Add(o);
28 }
29 #endregion
30
31 #region Constrators
32 public MyTalk()
33 {
34 InitializeComponent();
35 AddItem = new ListBoxAppendItem(addItem);
36 }
37 #endregion
38
39 #region Events
40 //Connect
41 private void btCnnect_Click(object sender, EventArgs e)
42 {
43 try
44 {
45 targetIP = IPAddress.Parse(txtTarget.Text.Trim());
46 clientThread = new Thread(new ThreadStart(clientConnect));
47 clientThread.IsBackground = true;
48 clientThread.Start();
49 }
50 catch (Exception exc)
51 {
52 listBox.Items.Add(exc.Message);
53 }
54 }
55 //Sent
56 private void btSent_Click(object sender, EventArgs e)
57 {
58 string str = txtMessage.Text;
59 if (!string.IsNullOrEmpty(str))
60 {
61 sent(str);
62 txtMessage.Clear();
63 }
64 }
65 //load and start listen
66 private void MyTalk_Load(object sender, EventArgs e)
67 {
68 serverThread = new Thread(new ThreadStart(startListen));
69 serverThread.IsBackground = true;
70 serverThread.Start();
71 }
72 #endregion
73
74 #region ClientMethods
75 void clientConnect()
76 {
77 clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
78 Socket s = clientSocket;
79 try
80 {
81 s.Connect(targetIP, 9898);
82 listBox.Invoke(AddItem, targetIP .ToString () +" - Connect Success!");
83 }
84 catch (Exception exc)
85 {
86 listBox.Invoke(AddItem, exc.Message);
87 }
88
89 }
90 void sent(string message)
91 {
92 byte[] buf = new byte[1024];
93 buf = System.Text.Encoding.Unicode.GetBytes (message );
94 try
95 {
96 clientSocket.Send(buf, buf.Length, SocketFlags.None);
97 listBox.Invoke(AddItem, "TO" + txtTarget.Text + message);
98 }
99 catch (Exception exc)
100 {
101 listBox .Invoke (AddItem ,exc.Message );
102 }
103 }
104 #endregion
105
106 #region ServerMethods
107 void startListen()
108 {
109 IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 9898);
110 serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
111 serverSocket.Bind(ipep);
112 serverSocket.Listen(10);
113 while (true)
114 {
115 try
116 {
117 receiveSocket = serverSocket.Accept();
118 receiveThread = new Thread(new ThreadStart(receiveData));
119 receiveThread.Start();
120 }
121 catch (SocketException sexc)
122 {
123 listBox.Invoke(AddItem, sexc .Message );
124 }
125 }
126 }
127 void receiveData()
128 {
129
130 int bufLen = 0;
131 byte[] buf = new byte[1024];
132 string data=null;
133 bool keepAlive = true;
134 Socket s = receiveSocket;
135 IPEndPoint ipep = (IPEndPoint)s.RemoteEndPoint;
136 while (keepAlive)
137 {
138 try
139 {
140 bufLen = s.Available;
141 s.Receive(buf, bufLen, SocketFlags.None);
142 data = System.Text.Encoding.Unicode.GetString(buf, 0, bufLen);
143 }
144 catch (SocketException sec)
145 {
146 listBox.Invoke(AddItem, sec.Message);
147 }
148 if(!string .IsNullOrEmpty (data))
149 listBox.Invoke(AddItem, (object)(Dns.GetHostEntry(ipep.Address.ToString()).HostName + "(" + ipep.Address + "):" + data.ToString()));
150 }
151
152
153
154 }
155 #endregion
156
157 }
158 }
159