求利用c#实现 服务器与客户端数据包传输 的例子
好像是要用到socket编程...?主要是想了解一下服务器端和客户端怎么建立连接,怎么在建立连接后传输数据.希望有收藏和有了解的朋友给点代码例子```--`教教小弟```...
好像是要用到socket编程...?
主要是想了解一下服务器端和客户端怎么建立连接,怎么在建立连接后传输数据.
希望有收藏和有了解的朋友给点代码例子```- -`
教教小弟````拜谢 分数献上!
如果比较多 麻烦发到这个地方--- jack87918@163.com 展开
主要是想了解一下服务器端和客户端怎么建立连接,怎么在建立连接后传输数据.
希望有收藏和有了解的朋友给点代码例子```- -`
教教小弟````拜谢 分数献上!
如果比较多 麻烦发到这个地方--- jack87918@163.com 展开
4个回答
展开全部
服务器端:
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 test4_1
{
public partial class Form1 : Form
{
Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
Socket client;
byte[] bytes = new byte[1024];
delegate void listboxDel(string s);
listboxDel listboxdel;
public Form1()
{
InitializeComponent();
textBoxContent.Focus();
listboxdel = new listboxDel(listbox);
Thread thread = new Thread(new ThreadStart(Listen));
thread.Start();
}
public void listbox(string str)
{
listShow.Items.Add(str);
listShow.SelectedIndex = listShow.Items.Count - 1;
listShow.ClearSelected();
}
//开始监听
private void Listen()
{
//获取IP地址,创建网络端点
string name = Dns.GetHostName();
IPAddress[] ipHostInfo = Dns.GetHostAddresses(name);
//网络端点
IPEndPoint localEP = new IPEndPoint(ipHostInfo[0], 82);
//处理用户连接请求
try
{
server.Bind(localEP); //绑定网络端口
server.Listen(10); //开始监听
AsyncCallback asyncCallback = new AsyncCallback(acceptCallback);
server.BeginAccept(asyncCallback,server);
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
}
//接受请求回调函数,并在该回调函数中调用接收数据
public void acceptCallback(IAsyncResult ar)
{
Socket server = (Socket)ar.AsyncState; //将返回的状态转换成为套接字(服务端套接字)
client = server.EndAccept(ar); //异步处理连接请求,创建新的客户端套接字handler处理远程通信
listShow.Invoke(listboxdel, "客户端连接成功!");
//接收数据
client.BeginReceive(bytes ,0 ,1000 ,SocketFlags.None ,new AsyncCallback(readCallback),client); //调用回调函数传送的状态参数
}
//接收数据回调函数
public void readCallback(IAsyncResult ar)
{
try
{
Socket handler = (Socket)ar.AsyncState; //将传递过来的接收状态转换成为socket实例
//结束挂起的接收操作,返回已读取的字节数
int read = handler.EndReceive(ar);
listShow.Invoke(listboxdel, Encoding.UTF8.GetString(bytes, 0, read));
handler.BeginReceive(bytes, 0, 1000, SocketFlags.None,new AsyncCallback(readCallback),handler);//继续读取
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void send(string str)
{
byte[] sendbyte=Encoding.UTF8.GetBytes(str);
client.BeginSend(sendbyte, 0, sendbyte.Length, SocketFlags.None, new AsyncCallback(sendCallBack), client);
}
private void sendCallBack(IAsyncResult ar)
{
Socket handler = (Socket)ar.AsyncState;
int bytesSent = handler.EndSend(ar);
listShow.Invoke(listboxdel, textBox1.Text + ":" + textBoxContent.Text);
}
private void buttonSend_Click(object sender, EventArgs e)
{
send(textBox1.Text + ":" + textBoxContent.Text);
}
}
}
客户端:
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 test4_2
{
public partial class Form1 : Form
{
Socket connectSocket;
//Socket client;
byte[] bytes = new byte[1024];
delegate void listboxDel(string s);
listboxDel listboxdel;
public Form1()
{
InitializeComponent();
textBoxContent.Focus();
listboxdel = new listboxDel(listbox);
//为连接指派线程
Thread threadConnect = new Thread(new ThreadStart(Connect));
threadConnect.Start();
}
public void listbox(string str)
{
listBox1.Items.Add(str);
listBox1.SelectedIndex = listBox1.Items.Count - 1;
listBox1.ClearSelected();
}
//连接方法
public void Connect()
{
try
{
//建立连接socket
connectSocket = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
//开始异步连接
connectSocket.BeginConnect(IPAddress.Parse("172.16.94.152"),
82,
new AsyncCallback(ConnectCallback), //定义回调函数代理
connectSocket); //传递给回调函数的状态
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
}
//连接方法的回调函数
private void ConnectCallback(IAsyncResult ar)
{
try
{
//从传递的状态中获取套接字,创建一个客户端套接字
Socket client = (Socket)ar.AsyncState;
//完成挂起的连接操作
client.EndConnect(ar);
listBox1.Invoke(listboxdel, "连接服务器成功,可以开始通话!");
client.BeginReceive(bytes, 0, 1000, 0, new AsyncCallback(receivecallback), client);
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
public void receivecallback(IAsyncResult ar)
{
try
{
Socket client = (Socket)ar.AsyncState;
int length = client.EndReceive(ar);
listBox1.Invoke(listboxdel, Encoding.UTF8.GetString(bytes, 0, length));
client.BeginReceive(bytes, 0, 1000, 0, new AsyncCallback(receivecallback), client);
}
catch
{
}
}
//发送方法
private void Send(String data)
{
//使用ASCII转换字符串为字节序列
byte[] byteData = Encoding.UTF8.GetBytes(data); //将字符串转换成字节序列
//开始向远端设备发送数据
connectSocket.BeginSend(byteData, 0, byteData.Length, SocketFlags.None,
new AsyncCallback(SendCallback), connectSocket);
}
//发送方法的回调函数
private void SendCallback(IAsyncResult ar)
{
try
{
//从传递的状态中获取套接字,创建一个客户端套接字
Socket client = (Socket)ar.AsyncState;
//结束异步数据传输操作,返回传输的字节数
int bytesSent = client.EndSend(ar);
listBox1.Invoke(listboxdel, textBoxUser.Text +":"+ textBoxContent.Text);
}
catch (Exception e)
{
MessageBox.Show(e.ToString());
}
}
private void buttonSend_Click(object sender, EventArgs e)
{
Send(textBoxUser.Text+":"+textBoxContent.Text);
}
}
}
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 test4_1
{
public partial class Form1 : Form
{
Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
Socket client;
byte[] bytes = new byte[1024];
delegate void listboxDel(string s);
listboxDel listboxdel;
public Form1()
{
InitializeComponent();
textBoxContent.Focus();
listboxdel = new listboxDel(listbox);
Thread thread = new Thread(new ThreadStart(Listen));
thread.Start();
}
public void listbox(string str)
{
listShow.Items.Add(str);
listShow.SelectedIndex = listShow.Items.Count - 1;
listShow.ClearSelected();
}
//开始监听
private void Listen()
{
//获取IP地址,创建网络端点
string name = Dns.GetHostName();
IPAddress[] ipHostInfo = Dns.GetHostAddresses(name);
//网络端点
IPEndPoint localEP = new IPEndPoint(ipHostInfo[0], 82);
//处理用户连接请求
try
{
server.Bind(localEP); //绑定网络端口
server.Listen(10); //开始监听
AsyncCallback asyncCallback = new AsyncCallback(acceptCallback);
server.BeginAccept(asyncCallback,server);
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
}
//接受请求回调函数,并在该回调函数中调用接收数据
public void acceptCallback(IAsyncResult ar)
{
Socket server = (Socket)ar.AsyncState; //将返回的状态转换成为套接字(服务端套接字)
client = server.EndAccept(ar); //异步处理连接请求,创建新的客户端套接字handler处理远程通信
listShow.Invoke(listboxdel, "客户端连接成功!");
//接收数据
client.BeginReceive(bytes ,0 ,1000 ,SocketFlags.None ,new AsyncCallback(readCallback),client); //调用回调函数传送的状态参数
}
//接收数据回调函数
public void readCallback(IAsyncResult ar)
{
try
{
Socket handler = (Socket)ar.AsyncState; //将传递过来的接收状态转换成为socket实例
//结束挂起的接收操作,返回已读取的字节数
int read = handler.EndReceive(ar);
listShow.Invoke(listboxdel, Encoding.UTF8.GetString(bytes, 0, read));
handler.BeginReceive(bytes, 0, 1000, SocketFlags.None,new AsyncCallback(readCallback),handler);//继续读取
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void send(string str)
{
byte[] sendbyte=Encoding.UTF8.GetBytes(str);
client.BeginSend(sendbyte, 0, sendbyte.Length, SocketFlags.None, new AsyncCallback(sendCallBack), client);
}
private void sendCallBack(IAsyncResult ar)
{
Socket handler = (Socket)ar.AsyncState;
int bytesSent = handler.EndSend(ar);
listShow.Invoke(listboxdel, textBox1.Text + ":" + textBoxContent.Text);
}
private void buttonSend_Click(object sender, EventArgs e)
{
send(textBox1.Text + ":" + textBoxContent.Text);
}
}
}
客户端:
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 test4_2
{
public partial class Form1 : Form
{
Socket connectSocket;
//Socket client;
byte[] bytes = new byte[1024];
delegate void listboxDel(string s);
listboxDel listboxdel;
public Form1()
{
InitializeComponent();
textBoxContent.Focus();
listboxdel = new listboxDel(listbox);
//为连接指派线程
Thread threadConnect = new Thread(new ThreadStart(Connect));
threadConnect.Start();
}
public void listbox(string str)
{
listBox1.Items.Add(str);
listBox1.SelectedIndex = listBox1.Items.Count - 1;
listBox1.ClearSelected();
}
//连接方法
public void Connect()
{
try
{
//建立连接socket
connectSocket = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
//开始异步连接
connectSocket.BeginConnect(IPAddress.Parse("172.16.94.152"),
82,
new AsyncCallback(ConnectCallback), //定义回调函数代理
connectSocket); //传递给回调函数的状态
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
}
//连接方法的回调函数
private void ConnectCallback(IAsyncResult ar)
{
try
{
//从传递的状态中获取套接字,创建一个客户端套接字
Socket client = (Socket)ar.AsyncState;
//完成挂起的连接操作
client.EndConnect(ar);
listBox1.Invoke(listboxdel, "连接服务器成功,可以开始通话!");
client.BeginReceive(bytes, 0, 1000, 0, new AsyncCallback(receivecallback), client);
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
public void receivecallback(IAsyncResult ar)
{
try
{
Socket client = (Socket)ar.AsyncState;
int length = client.EndReceive(ar);
listBox1.Invoke(listboxdel, Encoding.UTF8.GetString(bytes, 0, length));
client.BeginReceive(bytes, 0, 1000, 0, new AsyncCallback(receivecallback), client);
}
catch
{
}
}
//发送方法
private void Send(String data)
{
//使用ASCII转换字符串为字节序列
byte[] byteData = Encoding.UTF8.GetBytes(data); //将字符串转换成字节序列
//开始向远端设备发送数据
connectSocket.BeginSend(byteData, 0, byteData.Length, SocketFlags.None,
new AsyncCallback(SendCallback), connectSocket);
}
//发送方法的回调函数
private void SendCallback(IAsyncResult ar)
{
try
{
//从传递的状态中获取套接字,创建一个客户端套接字
Socket client = (Socket)ar.AsyncState;
//结束异步数据传输操作,返回传输的字节数
int bytesSent = client.EndSend(ar);
listBox1.Invoke(listboxdel, textBoxUser.Text +":"+ textBoxContent.Text);
}
catch (Exception e)
{
MessageBox.Show(e.ToString());
}
}
private void buttonSend_Click(object sender, EventArgs e)
{
Send(textBoxUser.Text+":"+textBoxContent.Text);
}
}
}
展开全部
客户端
static NetworkStream ns = null;
static void Main(string[] args)
{
//创建一个客户端程序
TcpClient client = new TcpClient();
client.Connect(IPAddress.Parse("127.0.0.1"),8888);
ns = client.GetStream();
Thread th = new Thread(new ThreadStart(ReadMsg));
th.Start();
StreamWriter sw = new StreamWriter(ns);
while (true)
{
sw.WriteLine(Console.ReadLine());
sw.Flush();
}
}
static void ReadMsg()
{
StreamReader sr = new StreamReader(ns);
while (true)
{
Console.WriteLine(sr.ReadLine());
}
}
服务端
static NetworkStream ns = null;
static void Main(string[] args)
{
//创建服务器监听器
TcpListener listener = new TcpListener(IPAddress.Parse("127.0.0.1"),8888);
//开启服务器监听程序
Console.WriteLine("服务器开始进行监听客户端的连接~~~~~!");
listener.Start();
//接收到一个连接队列中的客户端
TcpClient client = listener.AcceptTcpClient();
Console.WriteLine("接收到一个连接队列中的客户端");
//创建网络数据流用于发送和接收消息
ns = client.GetStream();
Thread th = new Thread(new ThreadStart(ReadMsg));
th.Start();
StreamWriter sw = new StreamWriter(ns);
while (true)
{
sw.WriteLine(Console.ReadLine());
sw.Flush();
}
}
static void ReadMsg() {
StreamReader sr = new StreamReader(ns);
while (true)
{
Console.WriteLine(sr.ReadLine());
}
}
把两段代码分别建个控制台应用程序
然后先启动服务端 再打开客户端就可以实现聊天了
窗体应用程序牵扯到线程问题 要麻烦些
static NetworkStream ns = null;
static void Main(string[] args)
{
//创建一个客户端程序
TcpClient client = new TcpClient();
client.Connect(IPAddress.Parse("127.0.0.1"),8888);
ns = client.GetStream();
Thread th = new Thread(new ThreadStart(ReadMsg));
th.Start();
StreamWriter sw = new StreamWriter(ns);
while (true)
{
sw.WriteLine(Console.ReadLine());
sw.Flush();
}
}
static void ReadMsg()
{
StreamReader sr = new StreamReader(ns);
while (true)
{
Console.WriteLine(sr.ReadLine());
}
}
服务端
static NetworkStream ns = null;
static void Main(string[] args)
{
//创建服务器监听器
TcpListener listener = new TcpListener(IPAddress.Parse("127.0.0.1"),8888);
//开启服务器监听程序
Console.WriteLine("服务器开始进行监听客户端的连接~~~~~!");
listener.Start();
//接收到一个连接队列中的客户端
TcpClient client = listener.AcceptTcpClient();
Console.WriteLine("接收到一个连接队列中的客户端");
//创建网络数据流用于发送和接收消息
ns = client.GetStream();
Thread th = new Thread(new ThreadStart(ReadMsg));
th.Start();
StreamWriter sw = new StreamWriter(ns);
while (true)
{
sw.WriteLine(Console.ReadLine());
sw.Flush();
}
}
static void ReadMsg() {
StreamReader sr = new StreamReader(ns);
while (true)
{
Console.WriteLine(sr.ReadLine());
}
}
把两段代码分别建个控制台应用程序
然后先启动服务端 再打开客户端就可以实现聊天了
窗体应用程序牵扯到线程问题 要麻烦些
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
Socket或者FTP 网上很多例子
发送端:先建立连接,然后转换数据到二进制流,然后传输
接收端:建立连接,接收二进制流,转换数据保存
发送端:先建立连接,然后转换数据到二进制流,然后传输
接收端:建立连接,接收二进制流,转换数据保存
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
请问你是87年9月18的生日吗
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询