首页 > 编程开发 > Objective-C编程 >
-
简单的C# socket编程
Server,服务器代码。
使用Socket套接字连接。
1using System;
Client,客户端程序,在文本框中输入字符,将在列表框显示。
2using System.Net;
3using System.Net.Sockets;
4using System.IO ;
5
6public class Echoserver
7{
8 //entry point of main method.
9 public static void Main()
10 {
11 //TcpListener is listening on the given port
12 Int32 port = 1234;
13
14 //IPAddress is connetct ip address
15 //IPAddress addr = IPAddress.Parse("127.0.0.1");
16 IPAddress ipAddress = Dns.Resolve("localhost").AddressList[0];
17
18 TcpListener tcpListener = new TcpListener(ipAddress,port);
19 tcpListener.Start();
20 Console.WriteLine("Server Started") ;
21 //Accepts a new connection
22 Socket socketForClient = tcpListener.AcceptSocket();
23 //StreamWriter and StreamReader Classes for reading and writing the data to and from.
24 //The server reads the meassage sent by the Client ,converts it to upper case and sends it back to the client.
25 //Lastly close all the streams.
26 try
27 {
28 if (socketForClient.Connected)
29 {
30 while(true)
31 {
32 Console.WriteLine("Client connected");
33 NetworkStream networkStream = new NetworkStream(socketForClient);
34 StreamWriter streamWriter = new StreamWriter(networkStream);
35 StreamReader streamReader = new StreamReader(networkStream);
36 string line = streamReader.ReadLine();
37 Console.WriteLine("Read:" +line);
38 line=line.ToUpper()+ "!";
39 streamWriter.WriteLine(line);
40 Console.WriteLine("Wrote:"+line);
41 streamWriter.Flush() ;
42 }
43 }
44 socketForClient.Close();
45 Console.WriteLine("Exiting");
46 }
47 catch(Exception e)
48 {
49 Console.WriteLine(e.ToString()) ;
50 }
51 }
52}
53
54
1using System;
2using System.Text;
3using System.Drawing;
4using System.Collections;
5using System.ComponentModel;
6using System.Windows.Forms;
7using System.Net;
8using System.Net.Sockets;
9using System.IO;
10
11namespace SocketSample
12{
13 public class Sample : System.Windows.Forms.Form
14 {
15 private System.Windows.Forms.Button btS;
16 private System.Windows.Forms.TextBox t1;
17 private NetworkStream networkStream ;
18 private StreamReader streamReader ;
19 private StreamWriter streamWriter ;
20 ArrayList sb;
21 TcpClient myclient;
22 bool flag=false;
23 private System.Windows.Forms.ListBox t2;
24
25 private System.ComponentModel.Container components = null;
26
27 public Sample()
28 {
29 sb = new ArrayList();
30 InitializeComponent();
31 if(!flag)
32 Connect();
33
34 //get a Network stream from the server
35 networkStream = myclient.GetStream();
36 streamReader = new StreamReader(networkStream);
37 streamWriter = new StreamWriter(networkStream);
38 ShowMessage();
39 }
40
41 protected override void Dispose( bool disposing )
42 {
43 if( disposing )
44 {
45 if(components != null)
46 {
47 components.Dispose();
48 }
49 }
50 base.Dispose( disposing );
51 }
52
53 Windows 窗体设计器生成的代码#region Windows 窗体设计器生成的代码
54 /**//// <summary>
55 /// 设计器支持所需的方法 - 不要使用代码编辑器修改
56 /// 此方法的内容。
57 /// </summary>
58 private void InitializeComponent()
59 {
60 System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(Sample));
61 this.t1 = new System.Windows.Forms.TextBox();
62 this.btS = new System.Windows.Forms.Button();
63 this.t2 = new System.Windows.Forms.ListBox();
64 this.SuspendLayout();
65 //
66 // t1
67 //
68 this.t1.Location = new System.Drawing.Point(24, 32);
69 this.t1.Name = "t1";
70 this.t1.Size = new System.Drawing.Size(280, 21);
71 this.t1.TabIndex = 0;
72 this.t1.Text = "";
73 this.t1.TextChanged += new System.EventHandler(this.t1_TextChanged);
74 //
75 // btS
76 //
77 this.btS.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("btS.BackgroundImage")));
78 this.btS.Enabled = false;
79 this.btS.FlatStyle = System.Windows.Forms.FlatStyle.Popup;
80 this.btS.Location = new System.Drawing.Point(320, 32);
81 this.btS.Name = "btS";
82 this.btS.TabIndex = 1;
83 this.btS.Text = "Send";
84 this.btS.Click += new System.EventHandler(this.btS_Click);
85 //
86 // t2
87 //
88 this.t2.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
89 this.t2.Font = new System.Drawing.Font("Courier New", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
90 this.t2.ItemHeight = 15;
91 this.t2.Location = new System.Drawing.Point(24, 64);
92 this.t2.Name = "t2";
93 this.t2.Size = new System.Drawing.Size(368, 212);
94 this.t2.TabIndex = 2;
95 //
96 // Sample
97 //
98 this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);
99 this.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("$this.BackgroundImage")));
100 this.ClientSize = new System.Drawing.Size(416, 297);
101 this.Controls.Add(this.t2);
102 this.Controls.Add(this.btS);
103 this.Controls.Add(this.t1);
104 this.Name = "Sample";
105 this.Text = "Sample";
106 this.ResumeLayout(false);
107
108 }
109 #endregion
110
111 public static void Main()
112 {
113 Sample df=new Sample();
114 df.FormBorderStyle=FormBorderStyle.Fixed3D;
115 Application.Run(df);
116 }
117
118 protected void Connect()
119 {
120 //connect to the "localhost" at the give port
121 //if you have some other server name then you can use that instead of "localhost"
122
123 try
124 {
125 sb.Add("Conneting to Server");
126 myclient = new TcpClient("localhost", 1234);
127 sb.Add("Conneted,Please enter something in the textbox");
128 }
129 catch
130 {
131 sb.Add(string.Format("Failed to connect to server at {0}:1234", "localhost"));
132 }
133 flag = true;
134 }
135
136 protected void ShowMessage()
137 {
138 for(int i=0;i<sb.Count;i++)
139 {
140 t2.Items.Add((object)sb[i].ToString());
141 }
142 sb.Clear();
143 }
144
145 private void t1_TextChanged(object sender, System.EventArgs e)
146 {
147 if(t1.Text == "" )
148 btS.Enabled = false;
149 else
150 btS.Enabled=true;
151 }
152
153 private void btS_Click(object sender, System.EventArgs e)
154 {
155 if(t1.Text=="")
156 {
157 sb.Add( "Please enter something in the textbox.");
158 t1.Focus();
159 return ;
160 }
161 string s;
162 try
163 {
164 streamWriter.WriteLine(t1.Text);
165 Console.WriteLine("Sending Message");
166 streamWriter.Flush();
167 s= streamReader.ReadLine();
168 Console.WriteLine("Reading Message") ;
169 Console.WriteLine(s) ;
170 sb.Add(s);
171 t1.Text = "";
172 t1.Focus();
173 ShowMessage();
174 }
175 catch
176 {
177 MessageBox.Show("Error.");
178 }
179 }
180 }
181}
182
1using System;
2using System.Text;
3using System.Drawing;
4using System.Collections;
5using System.ComponentModel;
6using System.Windows.Forms;
7using System.Net;
8using System.Net.Sockets;
9using System.IO;
10
11namespace SocketSample
12{
13 public class Sample : System.Windows.Forms.Form
14 {
15 private System.Windows.Forms.Button btS;
16 private System.Windows.Forms.TextBox t1;
17 private NetworkStream networkStream ;
18 private StreamReader streamReader ;
19 private StreamWriter streamWriter ;
20 ArrayList sb;
21 TcpClient myclient;
22 bool flag=false;
23 private System.Windows.Forms.ListBox t2;
24
25 private System.ComponentModel.Container components = null;
26
27 public Sample()
28 {
29 sb = new ArrayList();
30 InitializeComponent();
31 if(!flag)
32 Connect();
33
34 //get a Network stream from the server
35 networkStream = myclient.GetStream();
36 streamReader = new StreamReader(networkStream);
37 streamWriter = new StreamWriter(networkStream);
38 ShowMessage();
39 }
40
41 protected override void Dispose( bool disposing )
42 {
43 if( disposing )
44 {
45 if(components != null)
46 {
47 components.Dispose();
48 }
49 }
50 base.Dispose( disposing );
51 }
52
53 Windows 窗体设计器生成的代码#region Windows 窗体设计器生成的代码
54 /**//// <summary>
55 /// 设计器支持所需的方法 - 不要使用代码编辑器修改
56 /// 此方法的内容。
57 /// </summary>
58 private void InitializeComponent()
59 {
60 System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(Sample));
61 this.t1 = new System.Windows.Forms.TextBox();
62 this.btS = new System.Windows.Forms.Button();
63 this.t2 = new System.Windows.Forms.ListBox();
64 this.SuspendLayout();
65 //
66 // t1
67 //
68 this.t1.Location = new System.Drawing.Point(24, 32);
69 this.t1.Name = "t1";
70 this.t1.Size = new System.Drawing.Size(280, 21);
71 this.t1.TabIndex = 0;
72 this.t1.Text = "";
73 this.t1.TextChanged += new System.EventHandler(this.t1_TextChanged);
74 //
75 // btS
76 //
77 this.btS.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("btS.BackgroundImage")));
78 this.btS.Enabled = false;
79 this.btS.FlatStyle = System.Windows.Forms.FlatStyle.Popup;
80 this.btS.Location = new System.Drawing.Point(320, 32);
81 this.btS.Name = "btS";
82 this.btS.TabIndex = 1;
83 this.btS.Text = "Send";
84 this.btS.Click += new System.EventHandler(this.btS_Click);
85 //
86 // t2
87 //
88 this.t2.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
89 this.t2.Font = new System.Drawing.Font("Courier New", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
90 this.t2.ItemHeight = 15;
91 this.t2.Location = new System.Drawing.Point(24, 64);
92 this.t2.Name = "t2";
93 this.t2.Size = new System.Drawing.Size(368, 212);
94 this.t2.TabIndex = 2;
95 //
96 // Sample
97 //
98 this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);
99 this.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("$this.BackgroundImage")));
100 this.ClientSize = new System.Drawing.Size(416, 297);
101 this.Controls.Add(this.t2);
102 this.Controls.Add(this.btS);
103 this.Controls.Add(this.t1);
104 this.Name = "Sample";
105 this.Text = "Sample";
106 this.ResumeLayout(false);
107
108 }
109 #endregion
110
111 public static void Main()
112 {
113 Sample df=new Sample();
114 df.FormBorderStyle=FormBorderStyle.Fixed3D;
115 Application.Run(df);
116 }
117
118 protected void Connect()
119 {
120 //connect to the "localhost" at the give port
121 //if you have some other server name then you can use that instead of "localhost"
122
123 try
124 {
125 sb.Add("Conneting to Server");
126 myclient = new TcpClient("localhost", 1234);
127 sb.Add("Conneted,Please enter something in the textbox");
128 }
129 catch
130 {
131 sb.Add(string.Format("Failed to connect to server at {0}:1234", "localhost"));
132 }
133 flag = true;
134 }
135
136 protected void ShowMessage()
137 {
138 for(int i=0;i<sb.Count;i++)
139 {
140 t2.Items.Add((object)sb[i].ToString());
141 }
142 sb.Clear();
143 }
144
145 private void t1_TextChanged(object sender, System.EventArgs e)
146 {
147 if(t1.Text == "" )
148 btS.Enabled = false;
149 else
150 btS.Enabled=true;
151 }
152
153 private void btS_Click(object sender, System.EventArgs e)
154 {
155 if(t1.Text=="")
156 {
157 sb.Add( "Please enter something in the textbox.");
158 t1.Focus();
159 return ;
160 }
161 string s;
162 try
163 {
164 streamWriter.WriteLine(t1.Text);
165 Console.WriteLine("Sending Message");
166 streamWriter.Flush();
167 s= streamReader.ReadLine();
168 Console.WriteLine("Reading Message") ;
169 Console.WriteLine(s) ;
170 sb.Add(s);
171 t1.Text = "";
172 t1.Focus();
173 ShowMessage();
174 }
175 catch
176 {
177 MessageBox.Show("Error.");
178 }
179 }
180 }
181}
182