当前位置: 移动技术网 > IT编程>开发语言>.net > socket,模拟服务器、客户端通信

socket,模拟服务器、客户端通信

2019年04月20日  | 移动技术网IT编程  | 我要评论

翠微居小说网,宁波市江北区教育局,凯特琳 比德尔斯

服务器代码:

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 missuin
{
public partial class form2 : form
{
public form2()
{
initializecomponent();
}

private void button1_click(object sender, eventargs e)
{
//当点击开始监听的时候 在服务器端创建一个负责监ip地址和端口号的socket
socket socket = new socket(addressfamily.internetwork, sockettype.stream, protocoltype.ip);
ipaddress ip = ipaddress.any;//ipaddress.parse(txtserver.text);
//创建端口号对象
ipendpoint point = new ipendpoint(ip, convert.toint32(txtport.text));
//监听
socket.bind(point);
showmsg("监听成功");
socket.listen(10);

thread th = new thread(listen);
th.isbackground = true;
th.start(socket);
}


socket socketsend;
/// <summary>
/// 被线程所执行的函数,只能传object参数
/// </summary>
/// <param name="o"></param>
void listen(object o)
{
socket socketwatch = o as socket;
//等待客户端连接 并创建一个负责通信的sokcet
while (true)
{
//负责根客户通信的socket
socketsend = socketwatch.accept();
dictsocket.add(socketsend.remoteendpoint.tostring(), socketsend);

cbuusers.items.add(socketsend.remoteendpoint.tostring());
showmsg(socketsend.remoteendpoint.tostring() + ":" + "连接成功");
////客户端连接成功后,服务器应该接受客户端发来的消息
//byte[] buffer = new byte[1024 * 1024 * 2];
////实际接受到的有效字节数
//int r = socketsend.receive(buffer);
//string str = encoding.utf8.getstring(buffer, 0, r);
//console.writeline(socketsend.remoteendpoint+":"+str);
thread th = new thread(recive);
th.isbackground = true;
th.start(socketsend);
}
}

dictionary<string, socket> dictsocket = new dictionary<string, socket>();
/// <summary>
/// 服务器端不修改的接收客户发来的消息
/// </summary>
/// <param name="o"></param>
void recive(object o)
{
socket socketsend = o as socket;
while (true)
{
try
{
//客户端连接成功后,服务器应该接受客户端发来的消息
byte[] buffer = new byte[1024 * 1024 * 2];
//实际接受到的有效字节数
int r = socketsend.receive(buffer);
if (r == 0)
break;
string str = encoding.utf8.getstring(buffer, 0, r);
showmsg(socketsend.remoteendpoint + ":" + str);
}
catch (exception ex)
{
console.writeline(ex.message);
}
}
}

void showmsg(string msg)
{
txtlog.appendtext(msg + "\r\n");
}

private void form2_load(object sender, eventargs e)
{
control.checkforillegalcrossthreadcalls = false;
}
/// <summary>
/// 服务器给客户端发消息
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button5_click(object sender, eventargs e)
{
byte[] msgs = encoding.utf8.getbytes(this.txtmsg.text);

list<byte> list = new list<byte>();
list.add(0);
list.addrange(msgs);
byte[] newmsgs = list.toarray();
//获得用户在下拉框中选中的ip地址
string ip = cbuusers.selecteditem.tostring();
socket sendsocket = dictsocket[ip];
sendsocket.send(newmsgs);
showmsg(sendsocket.remoteendpoint + ":" + this.txtmsg.text);

}
/// <summary>
/// 选择要发送的文件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnselect_click(object sender, eventargs e)
{
openfiledialog of = new openfiledialog();
of.initialdirectory = @"c:\users";
of.title = "请选择要发送的文件";
of.filter = "所有文件|*.*";
of.showdialog();

txtpath.text = of.filename;

}

private void btnfilesend_click(object sender, eventargs e)
{
string path = this.txtpath.text.tostring();
using(filestream fs = new filestream(path, filemode.open, fileaccess.read))
{
byte[] buffer = new byte[1024 * 1024 * 5];
list<byte> list = new list<byte>();
list.add(1);
list.addrange(list);
byte[] newbytes = list.toarray();
socket socket = dictsocket[cbuusers.selecteditem.tostring()];
socket.send(newbytes);
}
}
private void button3_click(object sender, eventargs e)
{
byte[] buffer = new byte[1];
buffer[0] = 2;
socket socket = dictsocket[cbuusers.selecteditem.tostring()];
socket.send(buffer);
}
}
}

客户端代码

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 client
{
public partial class form1 : form
{
public form1()
{
initializecomponent();
}
//创建负责通信的socket
socket socketsend;
private void button1_click(object sender, eventargs e)
{
try
{
socketsend = new socket(addressfamily.internetwork, sockettype.stream, protocoltype.tcp);
ipaddress ip = ipaddress.parse(textbox1.text);
ipendpoint point = new ipendpoint(ip, convert.toint32(textbox2.text));
socketsend.connect(point);
showmsg("连接成功");

//开启一个新线程不停的接收服务器发来的消息
thread th = new thread(recive);
th.isbackground = true;
th.start();
}
catch(exception ex)
{

}
}

/// <summary>
/// 不停的接收服务器发来的消息
/// </summary>
void recive()
{
while (true)
{
byte[] buffer = new byte[1024 * 1024 * 2];
int r = socketsend.receive(buffer);
if (r == 0)
break;
//发来的是文字
if (buffer[0] == 0)
{
string s = encoding.utf8.getstring(buffer,1,r-1);
showmsg(socketsend.remoteendpoint + ":" + s);
}
else if (buffer[0] == 1)
{
savefiledialog sfd = new savefiledialog();
sfd.initialdirectory = @"c:\";
sfd.title = "请选择要保存的文件";
sfd.filter = "所有文件|*.*";
sfd.showdialog(this);
string path = sfd.filename;
using(filestream sf = new filestream(path, filemode.openorcreate, fileaccess.write))
{
sf.write(buffer, 1, r - 1);
}
messagebox.show("保存成功");
}
else if (buffer[0] == 2)
{
for (int i=0;i<10;i++){
this.location = new point(200, 200);
this.location = new point(210, 210);
}
}
}
}

private void showmsg(string msg)
{
this.txtlog.appendtext(msg + "\r\n");
}

private void button2_click(object sender, eventargs e)
{
byte[] msgs = system.text.encoding.utf8.getbytes(txtmsg.text);
socketsend.send(msgs);
}

private void form1_load(object sender, eventargs e)
{
control.checkforillegalcrossthreadcalls = false;
}
}
}

 

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网