首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > .NET > C# >

一个Socket的连接有关问题

2012-02-14 
一个Socket的连接问题我的代码中有以下一个函数:///summary///发送文本消息////summary///paramname

一个Socket的连接问题
我的代码中有以下一个函数:
              ///   <summary>
                ///   发送文本消息
                ///   </summary>
                ///   <param   name= "IP "> 目标IP </param>
                ///   <param   name= "msg "> 消息内容 </param>
                ///   <returns> 是否发送成功 </returns>
                public   static   bool   Send(IPAddress   IP,   string   msg)
                {
                        bool   tag   =   false;
                        _IPEP   =   new   IPEndPoint(IP,   _port);
                        if   (!_sendSocket.Connected)
                        {
                                _sendSocket.Connect(_IPEP);
                        }
                                if   (_sendSocket.Connected)
                                {
                                        MessageBox.Show( "Connection   Successful! ");
                                        byte[]   data   =   Encoding.ASCII.GetBytes(msg);
                                        byte[]   sizeinfo   =   new   byte[4];
                                        //could   optionally   call   BitConverter.GetBytes(data.length);
                                        sizeinfo[0]   =   (byte)data.Length;
                                        sizeinfo[1]   =   (byte)(data.Length   > >   8);
                                        sizeinfo[2]   =   (byte)(data.Length   > >   16);
                                        sizeinfo[3]   =   (byte)(data.Length   > >   24);
                                        _sendSocket.Send(sizeinfo);


                                        _sendSocket.Send(data);
                                        tag   =   true;
                                }
                                else
                                {
                                        MessageBox.Show( "Networks   block! ");
                                        tag   =   false;
                                }
                       
                        return   tag;
                }

当按send按钮,第一次调用的时候,是正常的,但第二次再调用的时候,运行到
                                _sendSocket.Connect(_IPEP);
就报错了,说 "a   connect   request   was   made   on   an   already   connected   socket ",
我是第一次写Socket,请大家帮忙看看,
谢谢了

[解决办法]
是不是没有关闭socket的原因:

加上这句试试:

_sendSocket.Send(sizeinfo);
_sendSocket.Send(data);
_sendSocket.Close();
[解决办法]
if (_sendSocket != null && !_sendSocket.Connected)
{
_sendSocket.Close();
_sendSocket = null;
_sendSocket = new Socket( AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp );
_sendSocket.Connect(_IPEP);
}
[解决办法]
socket没有关闭!同意BearRui(AK-47) ( )
[解决办法]
你的程序是单线运行的,也就是说,连接以后就直接去接收数据,而没有回去监听,接受完数据以后,就直接关闭。这样当然不可以的。给你一个比较简单的参考。

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;

// 客户端异步的对象
public class StateObject {
// 客户端
public Socket workSocket = null;
// 接收缓冲区大小
public const int BufferSize = 1024;
// 接收缓冲区
public byte[] buffer = new byte[BufferSize];
// 接收到的数据,放在一个StringBuilder里
public StringBuilder sb = new StringBuilder();
}

// 异步服务器类
public class AsynchronousSocketListener {
// 线程信号
public static ManualResetEvent allDone = new ManualResetEvent(false);

public AsynchronousSocketListener() {
}

public static void StartListening(int Port) {
// 接收缓冲
byte[] bytes = new Byte[1024];

// 定义终端

IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());


IPAddress ipAddress = ipHostInfo.AddressList[0];
IPEndPoint localEndPoint = new IPEndPoint(ipAddress, Port);

// 建立一个 TCP/IP socket.
Socket listener = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp );

// 将Socket绑定终端
try {
listener.Bind(localEndPoint);
listener.Listen(100); // 允许最多100个等待连接

while (true) {
// 设置同步信号
allDone.Reset();

// 开始异步监听
Console.WriteLine( "等待连接... ");
listener.BeginAccept(
new AsyncCallback(AcceptCallback),
listener );

// 阻塞当前线程,直到有一个客户端连接上来,这时候,会自动调用AcceptCallback这个方法
allDone.WaitOne();
}

} catch (Exception e) {
Console.WriteLine(e.ToString());
}

Console.WriteLine( "\nPress ENTER to continue... ");
Console.Read();

}
// 异步连接回调方法
public static void AcceptCallback(IAsyncResult ar) {
// 通知主线程可以继续接收连接了,从上面的allDone.WaitOne()这个地方继续运行
allDone.Set();

// 获得客户端的Socket
Socket listener = (Socket) ar.AsyncState;

// 服务端结束异步连接
Socket handler = listener.EndAccept(ar);

// 建立一个状态对象
StateObject state = new StateObject();
state.workSocket = handler;
// 开始客户端的异步接受数据
handler.BeginReceive( state.buffer, 0, StateObject.BufferSize, 0,
new AsyncCallback(ReadCallback), state);
}

// 异步接收数据的回调方法
public static void ReadCallback(IAsyncResult ar) {
String content = String.Empty;

// Retrieve the state object and the handler socket
// from the asynchronous state object.
StateObject state = (StateObject) ar.AsyncState;
Socket handler = state.workSocket;

// 结束接收.
int bytesRead = handler.EndReceive(ar);

if (bytesRead > 0) {
// 将当前所接收的存起来,继续接收,直到接收不到东西。
state.sb.Append(Encoding.ASCII.GetString(
state.buffer,0,bytesRead));

// Check for end-of-file tag. If it is not there, read
// more data.
content = state.sb.ToString();
if (content.IndexOf( " <EOF> ") > -1) {
// All the data has been read from the
// client. Display it on the console.
Console.WriteLine( "Read {0} bytes from socket. \n Data : {1} ",
content.Length, content );
// Echo the data back to the client.
Send(handler, content);
} else {
// Not all data received. Get more.
handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
new AsyncCallback(ReadCallback), state);
}
}
}

private static void Send(Socket handler, String data) {
// Convert the string data to byte data using ASCII encoding.
byte[] byteData = Encoding.ASCII.GetBytes(data);

// Begin sending the data to the remote device.
handler.BeginSend(byteData, 0, byteData.Length, 0,
new AsyncCallback(SendCallback), handler);
}

private static void SendCallback(IAsyncResult ar) {
try {
// Retrieve the socket from the state object.


Socket handler = (Socket) ar.AsyncState;

// Complete sending the data to the remote device.
int bytesSent = handler.EndSend(ar);
Console.WriteLine( "Sent {0} bytes to client. ", bytesSent);

handler.Shutdown(SocketShutdown.Both);
handler.Close();

} catch (Exception e) {
Console.WriteLine(e.ToString());
}
}


public static int Main(String[] args) {
StartListening();
return 0;
}
}

热点排行