C#通讯Socket使用和学习

展开阅读全文

关于c#socket通讯~

01-01

我想将我的服务器发送文件端改成----- 先选择要传送的文件 然后点击发送,这个发送按钮的功能就是先侦听端口,一旦有客户端连接上了就发送之前选择的文件。rn问题rn1,这样的设计是否可以实现客户端一连接上客户端就发送指定的文件rn2,我将发送部分的代码直接添加进针听得代码段,以实现我的这个功能,下面是我的代码,请大虾帮我看看那里错了rn我这样改了之后,实现不了客户端一连接就发送文件,我要连接的下位机是在Minigui 上跑得,是单任务的必须要这样做才可以发送文件rn谢谢大虾帮忙了 谢谢~~rnrn public void StartListen()rn rn int nPort = Convert.ToInt32(txtPort.Text);rn IPEndPoint ipLocalEndPoint;rn tryrn rn IPAddress ipAddress = Dns.GetHostByName(Dns.GetHostName()).AddressList[0];rn ipLocalEndPoint = new IPEndPoint(ipAddress, nPort); rn rn catch (SocketException socErr)rn rn label1.Text = socErr.Message;rn return;rn rn tryrn rn listenSoc = new JMFTCPSock(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);rn listenSoc.RemoteUserName = usernameTextBox.Text;rn listenSoc.Soc.Bind(ipLocalEndPoint);rn listenSoc.Soc.Listen(100);rn while (true)rn rn allDone.Reset();rn listenSoc.Soc.BeginAccept(new AsyncCallback(AcceptCallback), listenSoc);//接收请求 rn string filename = txtFileName.Text; ;rn int nPos = filename.LastIndexOf("\\");rn if (nPos > -1)rn filename = filename.Substring(nPos + 1);rn int nSoc;rnrn foreach (ListViewItem user in connListView.Items)rn rn tryrn rn nSoc = Convert.ToInt32(user.Text);rn if (clientSoc[nSoc] != null && user.Checked)rn rn if (clientSoc[nSoc].Soc.Connected)rn clientSoc[nSoc].SendFile(filename); rn rn label1.Text = filename +" has been sent!";rn rn catch (Exception err)rn rn label1.Text = "GetSock :" + err.Message;rn rn rn allDone.WaitOne();rn rn rn rn catch (Exception err)rn rn label1.Text = err.Message;rn rn rn rnpublic void AcceptCallback(IAsyncResult ar)rn rn tryrn rn allDone.Set();rn JMFTCPSock listener = (JMFTCPSock)ar.AsyncState;rn int nSoc = GetAvailbleSocket();rn clientSoc[nSoc].Soc = (Socket)listenSoc.Soc.EndAccept(ar); rn clientSoc[nSoc].SockRefNo = nSoc; rn ListViewItem item = new ListViewItem();rn item.Text = nSoc.ToString();rn item.Checked = true;rn rn item.SubItems.Add(clientSoc[nSoc].Soc.RemoteEndPoint.ToString());rn item.SubItems.Add(txtIP.Text);rn connListView.Items.Add(item);rn clientSoc[nSoc].ReceiveData();//接收消息rn rn rn catch (Exception err)rn rn label1.Text = "Accept :" + err.Message + err.Source.ToString();rn rn 论坛

C# socket通讯问题

05-30

C#使用socket通讯,客户端和服务端都在本机就能正常运行,但有时也会报错:由于目标主机积极拒绝.....,要是服务端和客户端放在在不同的机器上有时也会发生异常:由于目标主机积极拒绝。。,另外常常报异常:代码为:10061,无法建立连接!rn服务端关键代码如下:rnusing System;rnusing System.Collections.Generic;rnusing System.Text;rnusing System.Net.Sockets;rnusing System.Net;rnusing System.Threading;rnusing System.Runtime.Serialization.Formatters.Binary;rnusing System.IO;rnusing System.Collections;rnusing System.Runtime.Serialization;rnusing NetBarManagerModels;rnusing NetBarManagerBLL;rnnamespace NetBarManagerrnrn /**rn * 通讯专用处理类rn * rn */rn public class SocketManagerrn rn private static byte[] by = new byte[1024];rn private static Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);rn private static int port = 2000;//获取服务端侦听端口 rn private static string ip = "127.0.0.1";//获取服务端iprn private static IPAddress ipa = IPAddress.Parse(ip);rn private static IPEndPoint ipe = new IPEndPoint(ipa, port);rn private static Thread th;rn private static ArrayList clicentSocket = new ArrayList();//保存客户端Socketrn private static CardManager cardManager = new CardManager();//实例化上机卡处理类rn //序列化对象方法rn public static byte[] serializeobj(object obj)rn rn IFormatter formatter = new BinaryFormatter();rn MemoryStream ms = new MemoryStream();rn formatter.Serialize(ms, obj);rn byte[] tmp = ms.ToArray();rn ms.Close();rn return tmp;rn rn //反序列化方法rn public static object fanxuliehua(byte[] by)rn rn BinaryFormatter formatter = new BinaryFormatter();rn MemoryStream memoryStream = new MemoryStream(by);rn memoryStream.Position = 0;rn object RSOject = (object)formatter.Deserialize(memoryStream);rn memoryStream.Flush();rn memoryStream.Close();rn return RSOject;rn rn //获取服务端IP和端口rn public static void initPort() rn rn FileStream file = new FileStream("config.txt", FileMode.Open);rn StreamReader sr = new StreamReader(file);rn for (int i = 0; i < 4; i++) rn rn sr.ReadLine();rn rn ip = sr.ReadLine();//获取服务端iprn port = Convert.ToInt32(sr.ReadLine());//获取服务端侦听端口 rn sr.Close();rn file.Close();rn rn //开始侦听的方法rn public static void stratLis()rn rn initPort();rn s.Bind(ipe);rn s.Listen(100);rn rn //开始线程的方法rn public static void stratThread() rn rn th = new Thread(new ThreadStart(AcceptWorkThread));rn th.Start();rn rn //处理方法rn private static void AcceptWorkThread()rn rn Thread.CurrentThread.IsBackground = true;rn Socket t;rn t = s.Accept();rn if (t.Poll(10, SelectMode.SelectRead) && t != null)rn rn int num = t.Receive(by, by.Length, 0);rn if (fanxuliehua(by).GetType().Name == "TCard")//.GetType().Name用于判断是什么类型的对象rn rn TCard c = (TCard)fanxuliehua(by);rn TCard tc = vaildate(c);//判断卡号rn byte[] bys = new byte[1024];rn bys = serializeobj(tc);//将发送内容转化成字节码rn t.Send(bys, bys.Length, 0);//开始发送rn rn rn elsern rn //th.Abort();rn //t.Close();rn rnrn rn //客户端登录判断rn public static TCard vaildate(TCard t)rn rn TCard card =new TCard();rn int type=cardManager.IsCard(t.Number, t.CPass);//获取角色fkrn if (type>0)rn rn card = cardManager.GetTCardByNum(t.Number, type);rn rn return card;rn rn rnrnrn窗体调用的代码:rnusing System;rnusing System.Collections.Generic;rnusing System.Collections;rnusing System.ComponentModel;rnusing System.Data;rnusing System.Drawing;rnusing System.Text;rnusing System.Windows.Forms;rnusing NetBarManagerBLL;rnusing NetBarManagerModels;rnnamespace NetBarManagerrnrn public partial class ManagementMainForm : Formrn rn AdminsManager adminManager = new AdminsManager();//实例化管理员逻辑处理类rn public ManagementMainForm()rn rn InitializeComponent();rn rnrn private void AdvancedMainForm_Load(object sender, EventArgs e)rn rn this.lblAdminName.Text = adminManager.giveuser();//显示当前管理员rn this.lblTime.Text = DateTime.Now.ToString();//获取系统当前时间rn this.dgvComputer.DataSource = ComputerManager.getAllOnlinePC();rn SocketManager.stratLis();//开始侦听rn this.timerSocket.Enabled = true;rn rnrn /*rn*省略其他代码rn*rn*/rn //处理客户端请求rn private void timerSocket_Tick(object sender, EventArgs e)rn rn SocketManager.stratThread();rn 论坛

没有更多推荐了,返回首页