求一个最简单的c# C/S Socket 服务器端实例 异步

1.接收并保存客户端的传到服务器端的编号以及客户端与服务器端之间的连接.以便后面遍历.
2.可单独给某个客户端发送消息,也可以向所有客户端发送消息
3.可以查看客户端连接的情况,如果掉线,自动在列表中清除该客户端.
4千万不要随便档一段代码下来然后用.....省略其中代码
5.有注释的最好,没有也行

ps:初次接触Socket 不太清楚 希望高手 解答时 类同新手对待
邮件:tcliu1986@163.com

一楼的 基本上不晓得是么东西
最新回答
幽梦化蝶

2024-07-28 11:51:01

1.简单服务器端
/*
using System.Data;
using System.Net.Sockets;
using System.Net;
using System.Threading;
private static int port = %%2;
private static Thread thThreadRead;
private static TcpListener TcpListen;
private static bool bListener = true;
private static Socket stRead;
*/
private static void Listen()
{
try
{
TcpListen = new TcpListener(port);
TcpListen.Start();
stRead = TcpListen.AcceptSocket();
EndPoint tempRemoteEP = stRead.RemoteEndPoint;
IPEndPoint tempRemoteIP = (IPEndPoint)tempRemoteEP;
IPHostEntry host = Dns.GetHostByAddress(tempRemoteIP.Address);
string sHostName = host.HostName;
while (bListener)
{
stRead.Send(Encoding.ASCII.GetBytes(%%1));
string sTime = DateTime.Now.ToShortTimeString();
Byte[] byRead = new Byte[1024];
int iRead = stRead.ReceiveFrom(byRead, ref tempRemoteEP);
Byte[] byText = new Byte[iRead];
Array.Copy(byRead, 0, byText, 0, iRead);
string line = System.Text.Encoding.Default.GetString(byRead);
}
}
catch (System.Security.SecurityException)
{
//监听失败
}
}
thThreadRead = new Thread(new ThreadStart(Listen));
thThreadRead.Start();

2.简单客户端
/*
using System.Data;
using System.Net.Sockets;
using System.Net;
private static IPEndPoint dateTimeHost;
*/
string hostIPString=%%1;
string hostPortString=%%2;
IPAddress hostIP=IPAddress.Parse(hostIPString);
dateTimeHost=new IPEndPoint(hostIP,Int32.Parse(hostPortString));
Socket conn=new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
conn.Connect(dateTimeHost);
int bytes=0;
Byte[] RecvBytes=new Byte[256];
bytes=conn.Receive(RecvBytes,RecvBytes.Length,0);
string RecvString=Encoding.ASCII.GetString(RecvBytes,0,bytes);
Console.WriteLine(RecvString);
conn.Shutdown(SocketShutdown.Both);
conn.Close();

3.获得本机IP
//using System.Net;
IPAddress[] addressList = Dns.GetHostByName(Dns.GetHostName()).AddressList;
string %%1=null;
for (int i = 0; i < addressList.Length; i++)
{
%%1 += addressList[i].ToString();
}

5.点对点通信
/*
using System.Data;
using System.Net.Sockets;
using System.Net;
using System.Threading;
*/
Thread th;
TcpListener tpListen1;
bool listenerRun=true;
NetworkStream tcpStream;
StreamWriter reqStreamW;
TcpClient tcpc;
Socket skSocket;
protected void Listen()
{
try{
tpListen1=new TcpListener(Int32.Parse(%%2));
tpListen1.Start();
skSocket=tpListen1.AcceptSocket();
EndPoint tempRemoteEP=skSocket.RemoteEndPoint;
IPEndPoint tempRemoteIP=(IPEndPoint)tempRemoteEP;
IPHostEntry host=Dns.GetHostByAddress(tempRemoteIP.Address);
string HostName=host.HostName;
while(listenerRun)
{
Byte[] stream=new Byte[1024];
string time=DateTime.Now.ToString();
int i=skSocket.ReceiveFrom(stream,ref tempRemoteEP);
string %%5=Encoding.UTF8.GetString(stream);
//指定编码,从缓冲区中解析出内容
//time+" "+HostName+":"
}
}
catch(Security.SecurityException)
{
//防火墙安全错误!
}
try{
string sMsg=%%4;
string MyName=Dns.GetHostName();
reqStreamW=new StreamWriter(tcpStream);
reqStreamW.Write(sMsg);
reqStreamW.Flush();
string time=DateTime.Now.ToString();
//显示传送的数据和时间
//time+" "+MyName+":"
//sMsg
}
catch(Exception)
{
//无法发送信息到目标计算机!
}

protected override void Dispose(bool disposing)
{
try{
listenerRun=false;
th.Abort();
th=null;
tpListen1.Stop();
skSocket.Close();
tcpc.Close();
}
catch{}
if(disposing && component!=null)
{
components.Dispose();
}
}
base.Dispose(disposing);
}
16.聊天室服务器端逻辑
using System.Data;
using System.Net.Sockets;
using System.Net;
using System.Threading;
using System.Collections;
class Server
{
private static List<Socket> li = new ArrayList<Socket>();
private static TcpListener TcpListen;
private static Socket stRead;
public Server(int port)
{
try
{
TcpListen = new TcpListener(port);
TcpListen.Start();
}
catch (Exception) { }
}
public List<TcpListener> Li()
{
get{
return li;
};
set{
li=value;
};
}
public void start()
{
while (true)
{
Socket s;
try
{
stRead = TcpListen.AcceptSocket();
li.Add(TcpListen);
new Service(this, s).start();
}
catch (Exception e) { }
}

}
static void main(string[] args)
{
new Server(8888).start();
}
}

class Service
{
private static Socket stRead;
private static bool bListener = true;
private static TcpListener TcpListen;
public Service(Server server, Socket client)
{
TcpClient tcpc;
Socket stSend = null;
bool tcpConnect = false;
try
{
stSend = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
EndPoint tempRemoteEP = stSend.RemoteEndPoint;
IPEndPoint tempRemoteIP = (IPEndPoint)tempRemoteEP;
EndPoint epTemp = (EndPoint)tempRemoteIP;
stSend.Connect(epTemp);
tcpConnect = true;
}
catch (Exception)
{
//MessageBox.Show("目标计算机拒绝了连接请求!");
}
finally
{
if (tcpConnect)
{
stSend.Close();
}
}
}
public static void run()
{
while (true)
{
stRead = TcpListen.AcceptSocket();
EndPoint tempRemoteEP = stRead.RemoteEndPoint;
IPEndPoint tempRemoteIP = (IPEndPoint)tempRemoteEP;
IPHostEntry host = Dns.GetHostByAddress(tempRemoteIP.Address);
string sHostName = host.HostName;
while (bListener)
{
string sTime = DateTime.Now.ToShortTimeString();
Byte[] byRead = new Byte[1024];
int iRead = stRead.ReceiveFrom(byRead, ref tempRemoteEP);
Byte[] byText = new Byte[iRead];
Array.Copy(byRead, 0, byText, 0, iRead);
string line = System.Text.Encoding.Default.GetString(byRead);
}
}
}
static void Main(string[] args)
{
}
}

17.聊天室客户端逻辑
/*
类似qq聊天工具
你看看。。
这是客服端的代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.Net;
using System.Net.Sockets;

namespace demo2
{
public partial class frmTouchWe : Form
{
Thread a;
//发送IP跟端口
private UdpClient udp = new UdpClient("127.0.0.1",9000);
//接收端口
private UdpClient udpSend = new UdpClient(8000);
private IPEndPoint ip = new IPEndPoint(IPAddress.Any,0);
public frmTouchWe()
{
InitializeComponent();
Form.CheckForIllegalCrossThreadCalls = false;
}

private void frmTouchWe_Load(object sender, EventArgs e)
{ //定义线程开始
a = new Thread(new ThreadStart(Run));
a.Start(); }

private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
//客服接收信息。弹出窗体
frmAnswerInfo answerInfo = new frmAnswerInfo();
answerInfo.Show(); }

private void button1_Click(object sender, EventArgs e)
{
//在自己的信息栏中显示自己的信息
lsbInfo.Items.Add(txtInfo.Text);
//用户信息内容
string Mes = txtInfo.Text;
//用户信息
string mes = "用户:"+Program.user.id+"("+Program.user.name+")"+" " + time;
//转换成字节
byte[] b = UTF8Encoding.UTF8.GetBytes(Mes);
byte[] bb = UTF32Encoding.UTF8.GetBytes(mes);
//发送信息
udp.Send(bb, bb.Length);
udp.Send(b, b.Length);
txtInfo.Text = "";
}
//循环接受客服发来的信息
private void Run()
{
while (true)
{
byte[] b = udpSend.Receive(ref ip);
string mes = UTF8Encoding.UTF8.GetString(b);
lsbInfo.Items.Add(mes);
}
}

private void button2_Click(object sender, EventArgs e)
{
this.Close();
}

private void button3_Click_1(object sender, EventArgs e)
{
//清空所有项
lsbInfo.Items.Clear();
}
}
}

下面是服务器端的代码
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.Net;
using System.Net.Sockets;

namespace demo2
{
public partial class frmAnswerInfo : Form
{
//定义一条线程,用来循环接收客户发来的信息
Thread a;
//定义另一条线程,用来升起窗体
Thread b;
//发送到信息的地址
private UdpClient udpSend = new UdpClient("127.0.0.1",8000);
//接收端口
private UdpClient udp = new UdpClient(9000);
private IPEndPoint ip = new IPEndPoint(IPAddress.Any,0);
public frmAnswerInfo()
{
InitializeComponent();
Form.CheckForIllegalCrossThreadCalls = false;
}
//循环接收信息
private void Run()
{
while (true)
{
byte[] b = udp.Receive(ref ip);
string mes = UTF8Encoding.UTF8.GetString(b);
lsbInfo.Items.Add(mes);
}
}

private void frmAnswerInfo_Load(object sender, EventArgs e)
{
//设置窗体的位置属性(窗体加载时候慢慢从右下角升上来~类似qq广告~~)
this.Top = Screen.PrimaryScreen.WorkingArea.Height;
this.Left = Screen.PrimaryScreen.WorkingArea.Width - this.Width;
//设置窗体的名字
a = new Thread(new ThreadStart(Run));

b = new Thread(new ThreadStart(run));
//开始线程
a.Start();
b.Start();
}
//用户点击谈话时显示该窗体
private void run()
{
while (true)
{
this.Top = this.Top - 10;
Thread.Sleep(100);
if (Screen.PrimaryScreen.WorkingArea.Height - this.Height >= this.Top)
{
break;
}
}
}
//发送按钮编码
private void button1_Click(object sender, EventArgs e)
{
//获取当前时间
DateTime time = DateTime.Now;
//在自己的信息栏中显示自己发出去的信息
lsbInfo.Items.Add("在线客服:"+time);
lsbInfo.Items.Add(txtInfo.Text);

//在客户端显示自己的信息标题
string mes = "在线客服:"+time;
//信息内容
string Mes = txtInfo.Text;
//发送信息标题
byte[] b = UTF8Encoding.UTF8.GetBytes(mes);
//发送信息内容
byte[] bb = UTF8Encoding.UTF8.GetBytes(Mes);
udpSend.Send(b, b.Length);
udpSend.Send(bb,bb.Length);
txtInfo.Text = "";
}

private void button2_Click(object sender, EventArgs e)
{
this.Close();
}

private void button3_Click(object sender, EventArgs e)
{
//清除所有项
lsbInfo.Items.Clear();
}
}
}
*/
我想你会懂

2024-07-28 04:07:54

已经发给你了 代码很全 也有注释 基本能满足你的要求
我的邮箱 xuyevvcc@163.com
安和桥

2024-07-28 08:11:56

能给我也发一个例子么
洛筱爱

2024-07-28 06:56:39

这个是客户端