用C#在一台机器上实现服务器和客户端之间的通信(socket的小实验),哪位高手给我看看怎么编写?

2024-12-25 09:07:04
推荐回答(2个)
回答1:

socket_client
---------------------------------------------------------

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace socket_client
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
IPEndPoint end;
Socket s;
Thread td;

private void button1_Click(object sender, EventArgs e)
{
try
{
int port = Int32.Parse(textBox2.Text.Substring(textBox2.Text.LastIndexOf(":") + 1));
IPAddress ip = IPAddress.Parse(textBox1.Text.Substring(textBox1.Text.LastIndexOf(":") + 1));
end = new IPEndPoint(ip, port);

}
catch
{
MessageBox.Show("输入有误!!");
textBox1.Text = "IP:";
textBox2.Text = "端口:";
return;
}

try
{
s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
s.Connect(end);
label1.Text = "成功联接上服务器 " + textBox1.Text + ":" + textBox2.Text;
td = new Thread(new ThreadStart(bb));
td.IsBackground = true;
td.Start();
}
catch
{
label1.Text = "联接失败服务器!! ";
}

}

void bb()
{
while (true)
{

byte[] bb = new byte[1024];
int i= s.Receive(bb); //接收数据,返回每次接收的字节总数
string removeMsg = Encoding.Unicode.GetString(bb,0,i);

if (removeMsg == "cmd---exit")//收到的是退出通知
{
richTextBox1.Text = "";
label1.Text = "无连接";
DialogResult re=MessageBox.Show("服务器已经关闭.\n\"确定\"后退出程序,\n\"取消\"继续停留!", "消息提示:", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning);

MessageBox.Show(re.ToString());
if (re == DialogResult.OK)
{
sendExit();//告诉服务器我退出了
Application.Exit();
}
return;
}
richTextBox1.AppendText(removeMsg) ;
richTextBox1.ScrollToCaret();

}
}

private void button2_Click(object sender, EventArgs e)
{
string msg = "客户端说:" + richTextBox2.Text+"\n";
richTextBox1.AppendText(msg);
byte[] by = Encoding.Unicode.GetBytes(msg);
s.Send(by);
richTextBox2.Text = "";
richTextBox2.Focus();
richTextBox1.ScrollToCaret();

}

void sendExit()
{
string msg = "cmd---exit";
byte[] by = Encoding.Unicode.GetBytes(msg);
s.Send(by);
}
}
}

socket_server
-----------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace socket_server
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)
{
label1.Text = "监听端口" + Dns.GetHostByName(Dns.GetHostName()).AddressList[0] + ":" + Int32.Parse(textBox1.Text.Substring(textBox1.Text.LastIndexOf(":") + 1)) + "中......";
Thread td = new Thread(new ThreadStart(aa));
td.Start();
if (button1.Text == "开始监听")
{
button1.Text = "停止监听";

return;
}
else
{
sendExit();
ss.Shutdown(SocketShutdown.Both);
s.Close();
td.Abort();
label1.Text = "停止监听!";
richTextBox1.Text = "";
button1.Text = "开始监听";

}
}

void sendExit()
{
string msg = "cmd---exit";
byte[] by = Encoding.Unicode.GetBytes(msg);
ss.Send(by);
}
Socket s;
Socket ss;
void aa()
{

int port = Int32.Parse(textBox1.Text.Substring(textBox1.Text.LastIndexOf(":") + 1));

IPEndPoint end = new IPEndPoint(Dns.GetHostByName(Dns.GetHostName()).AddressList[0], port);
s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
s.Bind(end);
s.Listen(5);
ss=s.Accept();
if (ss.Connected)
{
label1.Text = "有客户端联接上端口:"+textBox1.Text;
while (true)
{
byte[] by = new byte[1024];
int i = ss.Receive(by);
string msg = Encoding.Unicode.GetString(by, 0, i);
if (msg == "cmd---exit")
{
label1.Text = "客户端已经取消连接!";
return;
}
richTextBox1.AppendText(msg);
richTextBox1.ScrollToCaret();
}
}

}

private void button2_Click(object sender, EventArgs e)
{
string m = "服务器说:" + richTextBox2.Text + "\n";
richTextBox1.AppendText(m);
byte[] by = Encoding.Unicode.GetBytes(m);
ss.Send(by);
richTextBox2.Text = "";
richTextBox2.Focus();
richTextBox1.ScrollToCaret();
}

private void button3_Click(object sender, EventArgs e)
{
string w="123455";
MessageBox.Show(w.Substring(0));
}
}
}

回答2:


TcpListener进行监听就可以了。
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;

class MyTcpListener
{
public static void Main()
{
TcpListener server=null;
try
{
// Set the TcpListener on port 13000.
Int32 port = 8000;
IPAddress localAddr = IPAddress.Parse("127.0.0.1");

// TcpListener server = new TcpListener(port);
server = new TcpListener(localAddr, port);

// Start listening for client requests.
server.Start();

// Buffer for reading data
Byte[] bytes = new Byte[4096];
String data = null;

// Enter the listening loop.
while(true)
{
Console.Write("Waiting for a connection... ");

// Perform a blocking call to accept requests.
// You could also user server.AcceptSocket() here.
TcpClient client = server.AcceptTcpClient();
Console.WriteLine("Connected!");

data = null;

// Get a stream object for reading and writing
NetworkStream stream = client.GetStream();

int i;

// Loop to receive all the data sent by the client.
while((i = stream.Read(bytes, 0, bytes.Length))!=0)
{
// Translate data bytes to a ASCII string.
data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
Console.WriteLine("Received: ", data);

// Process the data sent by the client.
data = data.ToUpper();

byte[] msg = System.Text.Encoding.ASCII.GetBytes(data);

// Send back a response.
stream.Write(msg, 0, msg.Length);
Console.WriteLine("Sent: ", data);
}

// Shutdown and end connection
client.Close();
}
}
catch(SocketException e)
{
Console.WriteLine("SocketException: ", e);
}
finally
{
// Stop listening for new clients.
server.Stop();
}

Console.WriteLine("\nHit enter to continue...");
Console.Read();
}
}

当然,官方的这个示例是单线程的,一次只能处理一个客户端,你可以将accept到的client扔到一个独立的线程,这样就可以多客户端并发处理了。