您的位置:首页 > 理论基础 > 计算机网络

C# 网络编程_socket实例

2012-11-08 21:41 525 查看
客户端:

//发送数据:

private void button1_Click(object sender, EventArgs e)
{
byte[] bytes = new byte[1024];
Socket sk1, sk2;
IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
IPAddress ipAddress = ipHostInfo.AddressList[0];
IPEndPoint remoteEP = new IPEndPoint(ipAddress, 11000);

sk1 = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
sk1.Connect(remoteEP);
byte[] msg = Encoding.Unicode.GetBytes(textBox1.Text);
int bytesSent = sk1.Send(msg);
int bytesRec = sk1.Receive(bytes);//接收返回数据(可略)
this.textBox2.Text= Encoding.Unicode.GetString(bytes, 0, bytesRec);
}
catch(Exception p)
{
MessageBox.Show(p.ToString());
}

}

服务器端:

Thread th1;

th1 = new Thread(StartListening);
th1.Start();

public void StartListening()
{
// Data buffer for incoming data.
byte[] bytes = new Byte[1024];

// Establish the local endpoint for the socket.
// Dns.GetHostName returns the name of the
// host running the application.
IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
IPAddress ipAddress = ipHostInfo.AddressList[0];
IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000);

// Create a TCP/IP socket.
Socket listener = new Socket(AddressFamily.InterNetwork,SocketType.Stream, ProtocolType.Tcp);

// Bind the socket to the local endpoint and
try
{
listener.Bind(localEndPoint);
listener.Listen(10);

// Start listening for connections.
while (true)
{
this.label1.Text="Waiting for a connection";
// Program is suspended while waiting for an incoming connection.
Socket handler = listener.Accept();
data = null;

// An incoming connection needs to be processed.
bytes = new byte[1024];
int bytesRec = handler.Receive(bytes);
data += Encoding.Unicode.GetString(bytes, 0, bytesRec);
string dt = data;
this.textBox1.Text = dt;

// Show the data

//this.textBox1.Text = data;

// Echo the data back to the client.
byte[] msg = Encoding.Unicode.GetBytes(data);

handler.Send(msg);
handler.Shutdown(SocketShutdown.Both);
handler.Close();
}

}
catch (Exception e)
{
MessageBox.Show(e.ToString());
}

}

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: