C#Socket 案例
服务器端
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
namespace wangluoqi
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
} private void button1_Click(object sender, EventArgs e)
{
//点击监听按钮时 创建Socket对像
Socket socketWatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//创建一个Socket对象,如果用UDP协议,则要用SocketTyype.Dgram类型的套接字 //声明ip地址
IPAddress ip = IPAddress.Any; //创建端口对像
IPEndPoint point = new IPEndPoint(ip, Convert.ToInt32(txtprot.Text)); //开始监听
socketWatch.Bind(point);
ShowMsg("监听成功");
//声明一秒内可同时连接的客户端
socketWatch.Listen(); //创建后台进程用来监听连接
Thread td = new Thread(listen);
td.IsBackground = true;
td.Start(socketWatch); }
Socket socketSend;
Dictionary<string, Socket> dc = new Dictionary<string, Socket>();
/// <summary>
/// 创建通信的客户端
/// </summary>
/// <param name="o"></param>
void listen(object o)
{
//把对像转成socket 如果不为socket 返回null
Socket socketwatch = o as Socket;
while (true)
{ //等待客户端连接 创建一个负责通信的Socket
socketSend = socketwatch.Accept();
dc.Add(socketSend.RemoteEndPoint.ToString(), socketSend);
comboBox1.Items.Add(socketSend.RemoteEndPoint.ToString());
ShowMsg(socketSend.RemoteEndPoint.ToString() + ":连接成功"); //新建一个进程,以免程序假死
Thread th = new Thread(Receive);
th.IsBackground = true;
th.Start(socketSend); }
} /// <summary>
/// 不停的接收传过来的数据
/// </summary>
/// <param name="o"></param>
void Receive(object o)
{
try
{
while (true)
{
Socket socketSend = o as Socket; byte[] buffer = new byte[ * * ];
int r = socketSend.Receive(buffer);
if (r == )
{
break;
}
string str = Encoding.UTF8.GetString(buffer, , r);
ShowMsg(socketSend.RemoteEndPoint + ":" + str);
}
}
catch { }
} private void ShowMsg(string str)
{
txtlog.AppendText(str + "\r\n");
} private void Form1_Load(object sender, EventArgs e)
{
//取消跨线层访问判断
Control.CheckForIllegalCrossThreadCalls = false;
} private void button4_Click(object sender, EventArgs e)
{
string str = txtsend.Text;
byte[] buf = Encoding.UTF8.GetBytes(str);
List<byte> blist = new List<byte>();
blist.Add();
blist.AddRange(buf);
//将泛型集合转为数组
byte[] nbuf = blist.ToArray(); if (comboBox1.SelectedItem == null)
{
comboBox1.SelectedIndex = ;
}
dc[comboBox1.SelectedItem.ToString()].Send(nbuf); // socketSend.Send(buf);
} private void button2_Click(object sender, EventArgs e)
{
OpenFileDialog odg = new OpenFileDialog();
odg.InitialDirectory = @"C:\Users\Administrator\Desktop";
odg.ShowDialog(); string filepath = odg.FileName;
txtfilename.Text = filepath; } //发送文本
private void button3_Click(object sender, EventArgs e)
{
string stpath = txtfilename.Text;
if (comboBox1.SelectedItem == null)
{
comboBox1.SelectedIndex = ;
}
using(FileStream fsRead=new FileStream(stpath,FileMode.OpenOrCreate,FileAccess.Read))
{
byte[] buf = new byte[ * * ];
int r = fsRead.Read(buf, , buf.Length);
List<byte> nlist= new List<byte>();
nlist.Add();
nlist.AddRange(buf);
//将集合转为数组;
byte[] nbuf = nlist.ToArray();
dc[comboBox1.SelectedItem.ToString()].Send(nbuf, , r+, SocketFlags.None);
}
} //发送窗口抖动
private void button5_Click(object sender, EventArgs e)
{
if (comboBox1.SelectedItem == null)
{
comboBox1.SelectedIndex = ;
}
byte[] buf = new byte[];
buf[] = ;
dc[comboBox1.SelectedItem.ToString()].Send(buf);
}
}
}
客户端
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms; namespace clent
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
Socket socketsend = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//连接服务器
private void button1_Click(object sender, EventArgs e)
{
//创建连接用的socket //创建连接点
IPAddress ip = IPAddress.Parse(txtip.Text);
//创建要连接的网络点
IPEndPoint point = new IPEndPoint(ip, Convert.ToInt32(txtpint.Text)); //连接
socketsend.Connect(point);
ShowMsg("连接成功"); //创建一个后台线层,用于接收服务器发来的数据
Thread td = new Thread(jssend);
td.IsBackground = true;
td.Start(); } /// <summary>
/// 接收数据
/// </summary>
void jssend()
{
try
{
while (true)
{ byte[] buf = new byte[ * * ];
//实际接收到的字符数
int r = socketsend.Receive(buf);
if (r == )
{
break;
}
//表示接收到的数据是文本
if (buf[] == )
{
string str = Encoding.UTF8.GetString(buf, , r-);
txtlog.AppendText(socketsend.RemoteEndPoint + ":" + str + "\r\n");
}
else if (buf[] == )//表示接收到的数据是文件
{
SaveFileDialog sdg = new SaveFileDialog();
sdg.InitialDirectory = @"C:\Users\Administrator\Desktop";
sdg.Title = "选择保存位置";
sdg.ShowDialog(this);//此处一定要添加this string filename = sdg.FileName;
using (FileStream fsw = new FileStream(filename, FileMode.OpenOrCreate, FileAccess.ReadWrite))
{
fsw.Write(buf, , r - );
}
MessageBox.Show("保存成功"); }
else if (buf[] == )//表示接收到的数据是窗口抖动
{
int x = this.Location.X;
int y = this.Location.Y;
for (int i = ; i < ; i++)
{
this.Location = new Point(x - , y - );
this.Location = new Point(x, y); }
} }
}
catch{}
} void ShowMsg(string str)
{
txtlog.AppendText(str + "\r\n");
} private void button2_Click(object sender, EventArgs e)
{
byte[] buf = Encoding.UTF8.GetBytes(txtsend.Text);
socketsend.Send(buf);
} private void Form1_Load(object sender, EventArgs e)
{
Control.CheckForIllegalCrossThreadCalls = false;
}
}
}
C#Socket 案例的更多相关文章
- 一个Android Socket的例子
1.开篇简介 Socket本质上就是Java封装了传输层上的TCP协议(注:UDP用的是DatagramSocket类).要实现Socket的传输,需要构建客户端和服务器端.另外,传输的数据可以是字符 ...
- 基于心跳的socket长连接
http://coach.iteye.com/blog/2024444 基于心跳的socket长连接 博客分类: http socket 案例: 心跳: socket模拟网页的报文连接某个网站,创建t ...
- 一个Android Socket的例子(转)
1.开篇简介 Socket本质上就是Java封装了传输层上的TCP协议(注:UDP用的是DatagramSocket类).要实现Socket的传输,需要构建客户端和服务器端.另外,传输的数据可以是字符 ...
- 网络编程系统化学习(1.1.)--socket基础
大纲 学完该阶段内容,你将会很好的完成如下的面试题 socket面试试题相关: 1.写一个简单的socket程序,实现客户端发送数据,服务端收到数据后,将该内容转发给客户端 2.简要概述一下socke ...
- python - socket通信笔记
参考: 通过编写聊天程序来熟悉python中多线程和socket的用法:https://www.cnblogs.com/mingjiatang/p/4905395.html python socket ...
- Java网络编程初探
IP地址案例 package ch17; import javax.swing.text.Style; import java.net.InetAddress; /** * Created by Ji ...
- python中网络编程基础
一:什么是c\s架构 1.c\s即client\server 客户端\服务端架构. 客户端因特定的请求而联系服务器并发送必要的数据等待服务器的回应最后完成请求 服务端:存在的意义就是等待客户端的请求, ...
- 1高并发server:多路IO之select
1 select A:select能监听的文件描写叙述符个数受限于FD_SETSIZE,一般为1024.单纯改变进程打开 的文件描写叙述符个数并不能改变select监听文件个数 B:解决1024 ...
- openresty开发系列36--openresty执行流程之6日志模块处理阶段
openresty开发系列36--openresty执行流程之6日志模块处理阶段 一)header_filter_by_lua 语法:header_filter_by_lua <lua-scri ...
随机推荐
- Symfony2源码分析——启动过程1
本文通过阅读分析Symfony2的源码,了解Symfony2启动过程中完成哪些工作,从阅读源码了解Symfony2框架. Symfony2的核心本质是把Request转换成Response的一个过程. ...
- 使用 Nuget打包类库
使用 Nuget打包类库 NuGet是个开源项目,项目包括 NuGet VS插件/NuGet Explorer/NuGetServer/NuGet命令行等项目,.NET Core项目完全使用Nuget ...
- Android 之 Spinner
1:activity_main.xml <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/androi ...
- PHP 中的数组
PHP中的数组是指一个键/值对的集合.PHP中的数组是使用哈系表构建的,这意味着访问每一个值都会有一个平均的O(1)复杂度. $arr=array([key=>]value,....); 在这里 ...
- Android系统的进程分类
1.前台进程:即当前正在前台运行的进程,说明用户当前正在与通过该进程与系统进行交互,所以该进程为最重要的进程,除非系统的内容已经到不堪重负的情况,否则系统是不会将改进程终止的.2.可见进程:一般还是显 ...
- LED驅動電路概述
LED是一種固體光源,當它兩端加上正向電壓,半導體中的少數載流子和多數載流子發生復合,放出的過剩能量將引起光子發射.采用不同的材料,可制成不同顏色有 發光二極管 . 隨著對LED研究的進一步深入,其光 ...
- ViewConfiguration滑动参数设置类
/** * 包含了方法和标准的常量用来设置UI的超时.大小和距离 */ public class ViewConfiguration { // 设定水平滚动条的宽度和垂直滚动条的高度,单位是像素px ...
- Android 使用Application总结
Application 配置全局Context 第一步.写一个全局的单例模式的MyApplication继承自Application 覆盖onCreate ,在这个方法里面实例化Application ...
- 【HDOJ】2585 Hotel
字符串水题. #include <cstdio> #include <cstring> #include <cstdlib> #define MAXN 55 cha ...
- [转]The culture name list in C#
Culture Names [C#] This example shows how to get all culture names in the .NET Framework. Use static ...