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.Runtime.InteropServices;
using System.IO;
using System.Diagnostics;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Drawing.Imaging;
//原理:
该程序利用socket接受服务端发送来的指令,解析出相应的操作,客户端根据指令调用对应的方法。
该程序适用于初学者项目参考,其实时运行效率有待考证。
namespace TestOnLine
{
public partial class 软帝考试系统 : Form
{
Graphics g;
Bitmap bmp;
Graphics g2;
Bitmap bmp2;
string pro = "{0}&{1}&{2}&{3}&{4}";//我的软件的协传输议
string userName = Dns.GetHostName();// 获取我的主机名
IPAddress ip;//我的ip
IPAddress firedIp;//教师端的ip
int port = 9305;//我的端口号
public void UdpSendMessage(IPAddress sendIp, string cmdNo, string msg)
{
Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
//发送的内容
string context = string.Format(pro, userName, ip, DateTime.Now.Ticks, cmdNo, msg);
byte[] buffer = Encoding.Default.GetBytes(context);
//指定发给谁
client.Connect(sendIp, port);
//发送
client.Send(buffer);
//关闭
client.Close();
}
public void SendData()
{
IPAddress ip = firedIp;//
Socket server = new Socket(AddressFamily.InterNetwork,
SocketType.Dgram, ProtocolType.Udp);
server.Connect(ip, port);
//server.SendBufferSize = 200000; //对udp协议没用
Rectangle rec1=new Rectangle (0,0,bmp.Width,bmp.Height);
Rectangle rec2=new Rectangle (0,0,bmp2.Width,bmp2.Height);
while (true)
{
//1
g.Clear(Color.White);
g.CopyFromScreen(0, 0, 0, 0, new Size(bmp.Width, bmp.Height));
g2.Clear(Color.White);
g2.DrawImage(bmp,rec2,rec1,GraphicsUnit.Pixel);
//2
//内存流,在内存中存在的流,不依赖于磁盘文件
MemoryStream ms = new MemoryStream();
bmp2.Save(ms, ImageFormat.Jpeg);
//将ms流中的所有内容拿出来
byte[] buffer = ms.GetBuffer();//得到这个流中的所有字节
int sendLen = 60000;
int times = buffer.Length / sendLen;
if (buffer.Length % sendLen != 0)
{
times++;
}
for (int i = 0; i < times - 1; i++)
{
server.Send(buffer,
i * sendLen, sendLen, SocketFlags.None);
}
server.Send(buffer, (times - 1) * sendLen,
buffer.Length - (times - 1) * sendLen, SocketFlags.None);
byte[] buf2 = new byte[1];//作为结束的标识