主页 > 编程资料 > C# >
发布时间:2015-09-26 作者:网络 阅读:213次

server,服务器代码。
使用Socket套接字连接。

using System;
using System.Net;
using System.Net.Sockets;
using System.IO ;

public class Echoserver
{
//entry point of main method.
public static void Main()
{
//TcpListener is listening on the given port
Int32 port = 1234;

//IPAddress is connetct ip address
//IPAddress addr = IPAddress.Parse("127.0.0.1",',',');
IPAddress ipAddress = Dns.Resolve("localhost").AddressList[0];

TcpListener tcpListener = new TcpListener(ipAddress,port,',',');
tcpListener.Start(,',',');
Console.WriteLine("Server Started") ;
//Accepts a new connection
Socket socketForClient = tcpListener.AcceptSocket(,',',');
//StreamWriter and StreamReader Classes for reading and writing the data to and from.
//The server reads the meassage sent by the Client ,converts it to upper case and sends it back to the client.
//Lastly close all the streams.
try
{
if (socketForClient.Connected)
{
while(true)
{
Console.WriteLine("Client connected",',',');
NetworkStream networkStream = new NetworkStream(socketForClient,',',');
StreamWriter streamWriter = new StreamWriter(networkStream,',',');
StreamReader streamReader = new StreamReader(networkStream,',',');
string line = streamReader.ReadLine(,',',');
Console.WriteLine("Read:" +line,',',');
line=line.ToUpper()+ "!";
streamWriter.WriteLine(line,',',');
Console.WriteLine("Wrote:"+line,',',');
streamWriter.Flush() ;
}
}
socketForClient.Close(,',',');
Console.WriteLine("Exiting",',',');
}
catch(Exception e)
{
Console.WriteLine(e.ToString()) ;
}
}
}


Client,客户端程序,在文本框中输入字符,将在列表框显示。
using System;
using System.Text;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.IO;

namespace SocketSample
{
public class Sample : System.Windows.Forms.Form
{
private System.Windows.Forms.Button btS;
private System.Windows.Forms.TextBox t1;
private NetworkStream networkStream ;
private StreamReader streamReader ;
private StreamWriter streamWriter ;
ArrayList sb;
TcpClient myclient;
bool flag=false;
private System.Windows.Forms.ListBox t2;

private System.ComponentModel.Container components = null;

public Sample()
{
sb = new ArrayList(,',',');
InitializeComponent(,',',');
if(!flag)
Connect(,',',');

//get a Network stream from the server
networkStream = myclient.GetStream(,',',');
streamReader = new StreamReader(networkStream,',',');
streamWriter = new StreamWriter(networkStream,',',');
ShowMessage(,',',');
}

protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose(,',',');
}
}
base.Dispose( disposing ,',',');
}

Windows 窗体设计器生成的代码#region Windows 窗体设计器生成的代码
/**////


/// 设计器支持所需的方法 - 不要使用代码编辑器修改
/// 此方法的内容。
///

private void InitializeComponent()
{
System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(Sample),',',');
this.t1 = new System.Windows.Forms.TextBox(,',',');
this.btS = new System.Windows.Forms.Button(,',',');
this.t2 = new System.Windows.Forms.ListBox(,',',');
this.SuspendLayout(,',',');
//
// t1
//
this.t1.Location = new System.Drawing.Point(24, 32,',',');
this.t1.Name = "t1";
this.t1.Size = new System.Drawing.Size(280, 21,',',');
this.t1.TabIndex = 0;
this.t1.Text = "";
this.t1.TextChanged += new System.EventHandler(this.t1_TextChanged,',',');
//
// btS
//
this.btS.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("btS.BackgroundImage")),',',');
this.btS.Enabled = false;
this.btS.FlatStyle = System.Windows.Forms.FlatStyle.Popup;
this.btS.Location = new System.Drawing.Point(320, 32,',',');
this.btS.Name = "btS";
this.btS.TabIndex = 1;
this.btS.Text = "Send";
this.btS.Click += new System.EventHandler(this.btS_Click,',',');
//
// t2
//
this.t2.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.t2.Font = new System.Drawing.Font("Courier New", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)),',',');
this.t2.ItemHeight = 15;
this.t2.Location = new System.Drawing.Point(24, 64,',',');
this.t2.Name = "t2";
this.t2.Size = new System.Drawing.Size(368, 212,',',');
this.t2.TabIndex = 2;
//
// Sample
//
this.AutoScaleBaseSize = new System.Drawing.Size(6, 14,',',');
this.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("$this.BackgroundImage")),',',');
this.ClientSize = new System.Drawing.Size(416, 297,',',');
this.Controls.Add(this.t2,',',');
this.Controls.Add(this.btS,',',');
this.Controls.Add(this.t1,',',');
this.Name = "Sample";
this.Text = "Sample";
this.ResumeLayout(false,',',');

}
#endregion

public static void Main()
{
Sample df=new Sample(,',',');
df.FormBorderStyle=FormBorderStyle.Fixed3D;
Application.Run(df,',',');
}

protected void Connect()
{
//connect to the "localhost" at the give port
//if you have some other server name then you can use that instead of "localhost"

try
{
sb.Add("Conneting to Server",',',');
myclient = new TcpClient("localhost", 1234,',',');
sb.Add("Conneted,Please enter something in the textbox",',',');
}
catch
{
sb.Add(string.Format("Failed to connect to server at {0}:1234", "localhost"),',',');
}
flag = true;
}

protected void ShowMessage()
{
for(int i=0;i {
t2.Items.Add((object)sb[i].ToString(),',',');
}
sb.Clear(,',',');
}

private void t1_TextChanged(object sender, System.EventArgs e)
{
if(t1.Text == "" )
btS.Enabled = false;
else
btS.Enabled=true;
}

private void btS_Click(object sender, System.EventArgs e)
{
if(t1.Text=="")
{
sb.Add( "Please enter something in the textbox.",',',');
t1.Focus(,',',');
return ;
}
string s;
try
{
streamWriter.WriteLine(t1.Text,',',');
Console.WriteLine("Sending Message",',',');
streamWriter.Flush(,',',');
s= streamReader.ReadLine(,',',');
Console.WriteLine("Reading Message") ;
Console.WriteLine(s) ;
sb.Add(s,',',');
t1.Text = "";
t1.Focus(,',',');
ShowMessage(,',',');
}
catch
{
MessageBox.Show("Error.",',',');
}
}
}
}

关键字词: