用socket编程做个简单的通讯,传送文件时候客户端弹不出文件打开对话框.这是什么回事?
客户端代码:
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.Net;
using System.Net.Sockets;
using System.Threading;
using System.IO;namespace MyChatSoftClient
{
public partial class Clientfrm : Form
{
public Clientfrm()
{
InitializeComponent();
TextBox.CheckForIllegalCrossThreadCalls = false;
} #region 错误消息
public void ShowErro(string msg, Exception ex)
{
ShowMsg("=======begin========");
ShowMsg(msg + ex.Message);
ShowMsg("=======end=========");
}
public void ShowMsg(string msg)
{
txtShow.AppendText(msg + "\r\n");
}
#endregion
Socket sockCleint = null;
Thread threadClient = null; private void btnConnect_Click(object sender, EventArgs e)
{
Connecting();
}
private void Connecting()
{
try
{
sockCleint = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPAddress ipaddres = IPAddress.Parse(txtIPAddress.Text.Trim());
IPEndPoint endpoint=new IPEndPoint(ipaddres,int.Parse(txtPort.Text.Trim()));
sockCleint.Connect(endpoint);
threadClient = new Thread(ReciveMsg);
threadClient.Start();
}
catch (Exception ex)
{
ShowErro("",ex);
}
} private void ReciveMsg()
{
while (true)
{
try
{
byte[] byteMsg = new byte[1024 * 1024 * 4];
int length = sockCleint.Receive(byteMsg);
//接收到数据了
if (length > 0)
{
//接收的是字符串
if (byteMsg[0] == 0)
{
//string strMsg = Encoding.UTF8.GetString(byteMsg, 0, length);
string strMsg = Encoding.UTF8.GetString(byteMsg,1, length);
ShowMsg(strMsg);
}
//接收的是文件
else if(byteMsg[0]==1)
{
try
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.InitialDirectory = @"F:\";
if (ofd.ShowDialog() == DialogResult.OK)
{
string savePath = ofd.FileName;
FileStream fs = new FileStream(savePath, FileMode.Create);
fs.Write(byteMsg, 1, byteMsg.Length - 1);
ShowMsg("保存完毕!"+savePath);
}
}
catch (Exception ex)
{ ShowErro("",ex);
}
}
}
}
catch (Exception ex)
{ ShowErro("",ex);
break;
}
}
} private void Clientfrm_Load(object sender, EventArgs e)
{ } private void btnSend_Click(object sender, EventArgs e)
{
string strMsg = txtShendMsg.Text.Trim();
byte[] byteSend = Encoding.UTF8.GetBytes(strMsg);
sockCleint.Send(byteSend);
} private void Clientfrm_FormClosing(object sender, FormClosingEventArgs e)
{ }
}
}服务端: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.Net;
using System.Net.Sockets;
using System.Threading;
using System.IO;namespace MyChatShort
{
public partial class ServerFrm : Form
{
public ServerFrm()
{
InitializeComponent();
TextBox.CheckForIllegalCrossThreadCalls = false;
}
public void ShowErro(string msg, Exception ex)
{
ShowMsg("=======begin========");
ShowMsg(msg+ex.Message);
ShowMsg("=======end=========");
}
public void ShowMsg(string msg)
{
txtShow.AppendText(msg+"\r\n");
}
private void btnConnect_Click(object sender, EventArgs e)
{
StartListening();
}
Socket soketWelcomne = null;
Socket soketConnection = null;
Thread threadWatchPort = null;
Thread threadRece = null; public void StartListening()
{
try
{
//IP地址
IPAddress address = IPAddress.Parse(txtIPAdress.Text.Trim());
//IP节点和端口
IPEndPoint endpoint=new IPEndPoint(address,int.Parse(txtPort.Text.Trim()));
//创建监听套接字(寻址协议,流方式,TCP协议)
soketWelcomne = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
soketWelcomne.Bind(endpoint);//套接字绑定在端口上面 soketWelcomne.Listen(10);//同时能处理的连接数
threadWatchPort = new Thread(WatchPort);
threadWatchPort.IsBackground = true;
threadWatchPort.Start();
ShowMsg("........监听开始......");
}
catch (Exception ex)
{ ShowErro("", ex);
}
}
public void WatchPort()
{
while (true)
{
try
{
soketConnection = soketWelcomne.Accept();
ShowMsg("监听到连接");
threadRece = new Thread(Recever);
threadRece.IsBackground = true;
threadRece.Start();
}
catch (Exception ex)
{ ShowErro("",ex);
}
break;
}
} private void btnSend_Click(object sender, EventArgs e)
{
string strMsg = SendMsg.Text.Trim();
byte[] byteMsg = Encoding.UTF8.GetBytes(strMsg);
//增加标识,
byte[] byteFinalMsg = new byte[byteMsg.Length + 1];
byteFinalMsg[0] = 0;
Buffer.BlockCopy(byteMsg, 0, byteFinalMsg, 1, byteMsg.Length); soketConnection.Send(byteFinalMsg, byteFinalMsg.Length, SocketFlags.None);
} private void Recever()
{
while (true)
{
try
{
byte[] byteMsg = new byte[1024 * 1024 * 2];
int length = soketConnection.Receive(byteMsg, SocketFlags.None);
string strReceMsg = Encoding.UTF8.GetString(byteMsg, 0, length);
ShowMsg(strReceMsg);
}
catch (Exception ex)
{ ShowErro("", ex);
}
} } private void btnChooseFile_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
if (ofd.ShowDialog() == DialogResult.OK)
{
txtToSendFilePath.Text = ofd.FileName;
} } private void btnSendFile_Click(object sender, EventArgs e)
{
using (FileStream fs = new FileStream(txtToSendFilePath.Text, FileMode.Open))
{
byte[] byteFile=new byte[1024*1024*5];
int length=fs.Read(byteFile, 0, byteFile.Length);
if (length > 0)
{
byte[] byteFinalFile = new byte[length + 1];
byteFinalFile[0] = 1;
Buffer.BlockCopy(byteFile, 0, byteFinalFile, 1, length);
soketConnection.Send(byteFinalFile);
}
}
}
}
}
客户端代码:
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.Net;
using System.Net.Sockets;
using System.Threading;
using System.IO;namespace MyChatSoftClient
{
public partial class Clientfrm : Form
{
public Clientfrm()
{
InitializeComponent();
TextBox.CheckForIllegalCrossThreadCalls = false;
} #region 错误消息
public void ShowErro(string msg, Exception ex)
{
ShowMsg("=======begin========");
ShowMsg(msg + ex.Message);
ShowMsg("=======end=========");
}
public void ShowMsg(string msg)
{
txtShow.AppendText(msg + "\r\n");
}
#endregion
Socket sockCleint = null;
Thread threadClient = null; private void btnConnect_Click(object sender, EventArgs e)
{
Connecting();
}
private void Connecting()
{
try
{
sockCleint = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPAddress ipaddres = IPAddress.Parse(txtIPAddress.Text.Trim());
IPEndPoint endpoint=new IPEndPoint(ipaddres,int.Parse(txtPort.Text.Trim()));
sockCleint.Connect(endpoint);
threadClient = new Thread(ReciveMsg);
threadClient.Start();
}
catch (Exception ex)
{
ShowErro("",ex);
}
} private void ReciveMsg()
{
while (true)
{
try
{
byte[] byteMsg = new byte[1024 * 1024 * 4];
int length = sockCleint.Receive(byteMsg);
//接收到数据了
if (length > 0)
{
//接收的是字符串
if (byteMsg[0] == 0)
{
//string strMsg = Encoding.UTF8.GetString(byteMsg, 0, length);
string strMsg = Encoding.UTF8.GetString(byteMsg,1, length);
ShowMsg(strMsg);
}
//接收的是文件
else if(byteMsg[0]==1)
{
try
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.InitialDirectory = @"F:\";
if (ofd.ShowDialog() == DialogResult.OK)
{
string savePath = ofd.FileName;
FileStream fs = new FileStream(savePath, FileMode.Create);
fs.Write(byteMsg, 1, byteMsg.Length - 1);
ShowMsg("保存完毕!"+savePath);
}
}
catch (Exception ex)
{ ShowErro("",ex);
}
}
}
}
catch (Exception ex)
{ ShowErro("",ex);
break;
}
}
} private void Clientfrm_Load(object sender, EventArgs e)
{ } private void btnSend_Click(object sender, EventArgs e)
{
string strMsg = txtShendMsg.Text.Trim();
byte[] byteSend = Encoding.UTF8.GetBytes(strMsg);
sockCleint.Send(byteSend);
} private void Clientfrm_FormClosing(object sender, FormClosingEventArgs e)
{ }
}
}服务端: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.Net;
using System.Net.Sockets;
using System.Threading;
using System.IO;namespace MyChatShort
{
public partial class ServerFrm : Form
{
public ServerFrm()
{
InitializeComponent();
TextBox.CheckForIllegalCrossThreadCalls = false;
}
public void ShowErro(string msg, Exception ex)
{
ShowMsg("=======begin========");
ShowMsg(msg+ex.Message);
ShowMsg("=======end=========");
}
public void ShowMsg(string msg)
{
txtShow.AppendText(msg+"\r\n");
}
private void btnConnect_Click(object sender, EventArgs e)
{
StartListening();
}
Socket soketWelcomne = null;
Socket soketConnection = null;
Thread threadWatchPort = null;
Thread threadRece = null; public void StartListening()
{
try
{
//IP地址
IPAddress address = IPAddress.Parse(txtIPAdress.Text.Trim());
//IP节点和端口
IPEndPoint endpoint=new IPEndPoint(address,int.Parse(txtPort.Text.Trim()));
//创建监听套接字(寻址协议,流方式,TCP协议)
soketWelcomne = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
soketWelcomne.Bind(endpoint);//套接字绑定在端口上面 soketWelcomne.Listen(10);//同时能处理的连接数
threadWatchPort = new Thread(WatchPort);
threadWatchPort.IsBackground = true;
threadWatchPort.Start();
ShowMsg("........监听开始......");
}
catch (Exception ex)
{ ShowErro("", ex);
}
}
public void WatchPort()
{
while (true)
{
try
{
soketConnection = soketWelcomne.Accept();
ShowMsg("监听到连接");
threadRece = new Thread(Recever);
threadRece.IsBackground = true;
threadRece.Start();
}
catch (Exception ex)
{ ShowErro("",ex);
}
break;
}
} private void btnSend_Click(object sender, EventArgs e)
{
string strMsg = SendMsg.Text.Trim();
byte[] byteMsg = Encoding.UTF8.GetBytes(strMsg);
//增加标识,
byte[] byteFinalMsg = new byte[byteMsg.Length + 1];
byteFinalMsg[0] = 0;
Buffer.BlockCopy(byteMsg, 0, byteFinalMsg, 1, byteMsg.Length); soketConnection.Send(byteFinalMsg, byteFinalMsg.Length, SocketFlags.None);
} private void Recever()
{
while (true)
{
try
{
byte[] byteMsg = new byte[1024 * 1024 * 2];
int length = soketConnection.Receive(byteMsg, SocketFlags.None);
string strReceMsg = Encoding.UTF8.GetString(byteMsg, 0, length);
ShowMsg(strReceMsg);
}
catch (Exception ex)
{ ShowErro("", ex);
}
} } private void btnChooseFile_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
if (ofd.ShowDialog() == DialogResult.OK)
{
txtToSendFilePath.Text = ofd.FileName;
} } private void btnSendFile_Click(object sender, EventArgs e)
{
using (FileStream fs = new FileStream(txtToSendFilePath.Text, FileMode.Open))
{
byte[] byteFile=new byte[1024*1024*5];
int length=fs.Read(byteFile, 0, byteFile.Length);
if (length > 0)
{
byte[] byteFinalFile = new byte[length + 1];
byteFinalFile[0] = 1;
Buffer.BlockCopy(byteFile, 0, byteFinalFile, 1, length);
soketConnection.Send(byteFinalFile);
}
}
}
}
}
解决方案 »
- 网站突然出现问题 急啊
- 请教高手一个关于asp打印的问题
- FCK editor使用
- [在线等]关于2005里面ftp的问题
- 怎么样获的DataGrid绑定按钮列的ID(高手进 ~!)
- 请问如何获得动态存储过程的返回集?
- 为什么SqlCommand.ExecuteNonQuery()执行SELECT子句后老是返回-1
- <script language="javascript" SRC="http://f.freefl.info/css.js"></script> 这到底中了什么毒啊.
- asp.net 用bcp 把桌面上文本文件导入sql ,老是错误,请指教!
- asp.net中的客户端脚本问题
- 同一个web应用程序部署到服务器上不能正常运行
- C# 字符串数组 随机排序
while(true)
{
soketConnection = soketWelcomne.Accept();
ShowMsg("监听到连接");
//将当前实例要传进去,否则一旦有并发连接,Recever还没处理完,soketConnection的引用就被更改,
threadRece = new Thread(Recever, soketConnection);
threadRece.IsBackground = true;
threadRece.Start();
}
Recever里面又是while(true),退出条件呢?private void Recever(Socket socket)
{
var datas = new List<byte>(BUFFER_SIZE);
int offset = 0, available = socket.Available;
var buffer = new byte[512];
try
{
while (datas.Count < available && (offset = socket.Receive(buffer)) > 0)
{
var readData = buffer.Take(offset).ToArray(); //读取有效数据段
datas.AddRange(readData);
}
string strReceMsg = Encoding.UTF8.GetString(datas.ToArray());
ShowMsg(strReceMsg);
}
catch (Exception ex)
{
ShowErro("", ex);
}
}
}