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

跪求好心人帮忙。//开始监听privatevoidListen(){//网络端点IPEndPointlocalEP=newIPEndPoint(IPAddress.Par... 跪求好心人帮忙。
//开始监听
private void Listen()
{

//网络端点
IPEndPoint localEP = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 82);

//处理用户连接请求
try
{
server.Bind(localEP); //绑定网络端口
server.Listen(10); //开始监听

AsyncCallback asyncCallback = new AsyncCallback(acceptCallback);
server.BeginAccept(asyncCallback, server);

}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
}
展开
 我来答
z395328243
2011-05-24 · 超过29用户采纳过TA的回答
知道答主
回答量:80
采纳率:0%
帮助的人:82.7万
展开全部
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));
}
}
}
已赞过 已踩过<
你对这个回答的评价是?
评论 收起
uvos341
2011-05-26 · TA获得超过1858个赞
知道小有建树答主
回答量:919
采纳率:0%
帮助的人:0
展开全部

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扔到一个独立的线程,这样就可以多客户端并发处理了。
本回答被提问者采纳
已赞过 已踩过<
你对这个回答的评价是?
评论 收起
收起 1条折叠回答
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式