I have a server in C that send message to unity. In Unity, I can receive data once, but when the server sends a new message, unity receives nothing.
For example: Unity can connect to server, receive the first message that said "move right" and move the camera of Unity to the right but then if the server send "move left" or anything else unity is block in the function receive which calls BeginReceive:
client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
new AsyncCallback(ReceiveCallback), state);
Code of my server:
void connectToUnity() {
SOCKADDR_IN sin;
WSAStartup(MAKEWORD(2, 0), &WSAData);
sock = socket(AF_INET, SOCK_STREAM, 0);
sin.sin_addr.s_addr = inet_addr("127.0.0.1");
sin.sin_family = AF_INET;
sin.sin_port = htons(53660);
bind(sock, (SOCKADDR*)&sin, sizeof(sin));
listen(sock, 0);
printf("Connexion to unity\n");
}
void sendDataToUnity(const char * mouvement) {
SOCKET csock;
while (1)
{
int sinsize = sizeof(csin);
if ((csock = accept(sock, (SOCKADDR*)&csin, &sinsize)) != INVALID_SOCKET)
{
send(csock, mouvement, 14, 0);
printf("Donnees envoyees \n");
return;
}
else {
printf("Rien n'a ete envoye");
}
}
}
Code in Unity:
public bool ConnectToServer(string hostAdd, int port)
{
//connect the socket to the server
try
{
//create end point to connect
conn = new IPEndPoint(IPAddress.Parse(hostAdd), port);
//connect to server
clientSocket.BeginConnect(conn, new AsyncCallback(ConnectCallback), clientSocket);
socketReady = true;
connectDone.WaitOne();
Debug.Log("Client socket ready: " + socketReady);
// Receive the response from the remote device.
Receive(clientSocket);
//receiveDone.WaitOne();
}
catch (Exception ex)
{
Debug.Log("socket error: " + ex.Message);
}
return socketReady;
}
//async call to connect
static void ConnectCallback(IAsyncResult ar)
{
try
{
// Retrieve the socket
Socket client = (Socket)ar.AsyncState;
// Complete the connection
client.EndConnect(ar);
Debug.Log("Client Socket connected to: " + client.RemoteEndPoint);
connectDone.Set();
}
catch (Exception e)
{
Debug.Log("Error connecting: " + e);
}
}
private static void Receive(Socket client)
{
try
{
Debug.Log("Try to receive");
// Create the state object.
StateObject state = new StateObject();
state.workSocket = client;
// Begin receiving the data from the remote device.
client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
new AsyncCallback(ReceiveCallback), state);
}
catch (Exception e)
{
Debug.Log(e);
}
}
static void ReceiveCallback(IAsyncResult ar)
{
try
{
//Read data from the remote device.
Debug.Log("receive callback");
StateObject state = (StateObject)ar.AsyncState;
Socket client = state.workSocket;
int bytesRead = client.EndReceive(ar);
if (bytesRead > 0)
{
Debug.Log("Il y a une réponse");
state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, bytesRead));
client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
new AsyncCallback(ReceiveCallback), state);
response = state.sb.ToString();
Debug.Log(response);
//client.Shutdown(SocketShutdown.Both);
}
else
{
if(state.sb.Length > 1)
{
response = state.sb.ToString();
Debug.Log(response);
}
}
}
catch (Exception ex)
{
Debug.Log("Error: " + ex.Message);
}
}
The function receive is called once in the function ConnectToServer, then I tried to call again in the update like this:
void Update()
{
if (response.Contains("right"))
{
Debug.Log("Move to the right ");
float x = Camera.main.transform.localEulerAngles.x;
float y = Camera.main.transform.localEulerAngles.y;
DeplacementCamera.moveRight(x, y);
response = "";
Receive(clientSocket);
}
}
I have already see this post but without success or maybe I tried it in the wrong way:
Why does BeginReceive() not return for more than one read?
Edit: In the function ReceiveCallback the else is never reached.
you may change your method
private void SetupReceiveCallback(Socket sock)
{
try
{
DataBuffer = new byte[BufferSize];
AsyncCallback recieveData = new AsyncCallback(OnRecievedData);
sock.BeginReceive(DataBuffer, 0, DataBuffer.Length, SocketFlags.None, recieveData, _socket);
}
catch (Exception E)
{
}
}
private void OnRecievedData(IAsyncResult ar)
{
Socket sock = (Socket)ar.AsyncState;
try
{
if (sock.Connected)
{
int nBytesRec = sock.EndReceive(ar);
if (nBytesRec > 0)
{
string Data = Encoding.UTF8.GetString(DataBuffer);
if (Data.Length != 4)
{
string JsonString = Data;
if (!string.IsNullOrEmpty(JsonString))
{
try
{
//Add you code processing here
}
catch (Exception ex)
{
}
}
BufferSize = 4;
}
else
{
BufferSize = BitConverter.ToInt32(DataBuffer, 0);
}
}
SetupReceiveCallback(sock);
}
else
// on not connected to socket
}
catch (Exception E)
{
}
}
public bool Connect(string IP, int Port)
{
try
{
_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//if (IsValidIP(IP))
//{
// IPEndPoint epServer = new IPEndPoint(IPAddress.Parse(IP), Port);
// _socket.Connect(epServer);
//}
//else
//{
// _socket.Connect(IP, Port);
//}
//SetupReceiveCallback(_socket);
}
catch(Exception ex)
{
}
return false;
}
Related
I have a WPF 'server' app using a socket, with a UWP 'client' app using StreamSocket. I can transfer small amounts of data fine, but if I try and send a 288kb file, the file is received fine by the WPF app but the UWP app never receives the response.
WPF code:
In the ReadCallback method, the content is sent in the format of command;printername{data}. The data is all received fine but the Send method called before processing the data is not received.
public void Start()
{
Task.Run(() =>
{
var ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
var ipAddress = ipHostInfo.AddressList.FirstOrDefault(x =>x.AddressFamily == AddressFamily.InterNetwork);
var localEndPoint = new IPEndPoint(ipAddress, Settings.Default.PrintPort);
listener = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
try
{
listener.Bind(localEndPoint);
listener.Listen(100);
IsRunning = true;
while (true)
{
// Set the event to nonsignaled state.
AllDone.Reset();
// Start an asynchronous socket to listen for connections.
listener.BeginAccept(
AcceptCallback,
listener);
// Wait until a connection is made before continuing.
AllDone.WaitOne();
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
});
}
public void AcceptCallback(IAsyncResult ar)
{
if(!IsRunning) return;
// Signal the main thread to continue.
AllDone.Set();
// Get the socket that handles the client request.
Socket handler = listener.EndAccept(ar);
// Create the state object.
StateObject state = new StateObject {WorkSocket = handler};
handler.BeginReceive(state.Buffer, 0, StateObject.BufferSize, 0,
ReadCallback, state);
}
public static void ReadCallback(IAsyncResult ar)
{
try
{
// Retrieve the state object and the handler socket
// from the asynchronous state object.
StateObject state = (StateObject)ar.AsyncState;
Socket handler = state.WorkSocket;
// Read data from the client socket.
int bytesRead = handler.EndReceive(ar);
if (bytesRead > 0)
{
// There might be more data, so store the data received so far.
state.Sb.Append(Encoding.ASCII.GetString(
state.Buffer, 0, bytesRead));
// Check for end-of-file tag. If it is not there, read
// more data.
var content = state.Sb.ToString();
if (content.IndexOf("<EOF>") > -1)
{
content = content.Remove(content.IndexOf("<EOF>"));
if (content.StartsWith("PrintFile"))
{
if (!content.Contains("{"))
{
Send(handler, "false");
return;
}
var parts = content.Substring(0, content.IndexOf('{')).Split(';');
if (string.IsNullOrEmpty(parts[1]))
{
Send(handler, "false");
return;
}
// This send never gets received
Send(handler, "true");
//But the file is printed
var base64 = content.Substring(content.IndexOf('{') + 1);
base64 = base64.Remove(base64.LastIndexOf('}'));
var doc = new Spire.Pdf.PdfDocument(Convert.FromBase64String(base64));
doc.PrintSettings.PrinterName = parts[1];
doc.Print();
}
}
else
{
// Not all data received. Get more.
handler.BeginReceive(state.Buffer, 0, StateObject.BufferSize, 0,
ReadCallback, state);
}
}
}
catch
{
//Ignore
}
}
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,
SendCallback, handler);
}
private static void SendCallback(IAsyncResult ar)
{
try
{
// Retrieve the socket from the state object.
Socket handler = (Socket)ar.AsyncState;
handler.Shutdown(SocketShutdown.Both);
handler.Close();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
UWP Code:
public bool PrintFlle(string printer, string base64)
{
try
{
var result = Send($"PrintFile;{printer}{{{base64}}}<EOF>").Result;
return bool.TryParse(result, out var b) && b;
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
finally
{
socket.Dispose();
}
}
private async Task<string> Send(string input)
{
try
{
socket = new StreamSocket();
await socket.ConnectAsync(HostName, App.LocalSettings.Values["PrintPort"] as string);
using (Stream outputStream = socket.OutputStream.AsStreamForWrite())
{
using (var streamWriter = new StreamWriter(outputStream))
{
await streamWriter.WriteLineAsync(input);
await streamWriter.FlushAsync();
}
}
using (Stream inputStream = socket.InputStream.AsStreamForRead())
{
using (StreamReader streamReader = new StreamReader(inputStream))
{
var output = await streamReader.ReadLineAsync();
socket.Dispose();
return output;
}
}
}
catch (Exception e)
{
socket.Dispose();
return "";
}
}
I've created a basic C# application that is receiving and sending data with sockets. Currently I'm able to send data from my client to my server and I can receive response.
My problem is: As a client I don't know how to check if the server has send me anything new. Normally I send something as client and receive response there is no problem but sometimes server has to send me some information.
This is my current code sample, I'll update this post if I change the code
My server side code is like this:
public class StateObject
{
// Client socket.
public Socket workSocket = null;
// Size of receive buffer.
public const int BufferSize = 1024;
// Receive buffer.
public byte[] buffer = new byte[BufferSize];
// Received data string.
public StringBuilder sb = new StringBuilder();
}
public static ManualResetEvent allDone = new ManualResetEvent(false);
public void StartListening()
{
IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
IPAddress ipAddress = ipHostInfo.AddressList[0];
IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 10101);
Socket listener = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
try
{
listener.Bind(localEndPoint);
listener.Listen(10);
while (true)
{
allDone.Reset();
listener.BeginAccept(new AsyncCallback(AcceptCallback), listener);
allDone.WaitOne();
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
public void AcceptCallback(IAsyncResult ar)
{
allDone.Set();
Socket listener = (Socket)ar.AsyncState;
Socket handler = listener.EndAccept(ar);
StateObject state = new StateObject();
state.workSocket = handler;
ClientList.Add(handler);
handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReadCallback), state);
}
public void ReadCallback(IAsyncResult ar)
{
string content = string.Empty;
StateObject state = (StateObject)ar.AsyncState;
Socket handler = state.workSocket;
int bytesRead = handler.EndReceive(ar);
if (bytesRead > 0)
{
state.sb.Append(Encoding.UTF8.GetString(state.buffer, 0, bytesRead));
content = state.sb.ToString();
if (content.IndexOf("_|_!#*#_") > -1)
{
HandleIncomingMessage(handler, content.Substring(0, content.Length - 8));
}
else
{
handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReadCallback), state);
}
}
}
private void HandleIncomingMessage(Socket handler, string data)
{
CheckForIllegalCrossThreadCalls = false;
Response response = new Response();
byte[] byteData = Encoding.UTF8.GetBytes(data);
listView1.Items.Add(data);
response = ParserToSocket(data);
if (response == null)
{
response = new Response();
response.Status = "false";
response.Message = "Json not valid" + data;
}
if (response.Status == null)
response.Status = "false";
if (response.Message == null)
response.Message = "Error while creating response message";
byte[] ByteArrayToSend = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(response) + "_|_!#*#_");
handler.BeginSend(ByteArrayToSend, 0, ByteArrayToSend.Length, 0, new AsyncCallback(SendCallback), handler);
}
private void SendCallback(IAsyncResult ar)
{
try
{
StateObject.BufferSize, 0, new AsyncCallback(ReadCallback), state);
Socket handler = (Socket)ar.AsyncState;
int bytesSent = handler.EndSend(ar);
StateObject state = (StateObject)ar.AsyncState;
handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReadCallback), state);
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
and this is code for my client side :
public class StateObject
{
public Socket workSocket = null;
public const int BufferSize = 512;
public byte[] buffer = new byte[BufferSize];
public StringBuilder sb = new StringBuilder();
}
private string response = string.Empty;
public Socket ConnectedSocket;
IPHostEntry ipHostInfo;
IPAddress ipAddress;
IPEndPoint remoteEP;
private string StartClient()
{
try
{
ipHostInfo = Dns.GetHostEntry("127.0.0.1");
ipAddress = ipHostInfo.AddressList[0];
remoteEP = new IPEndPoint(ipAddress, 10101);
ConnectedSocket = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
ConnectedSocket.BeginConnect(remoteEP, new AsyncCallback(ConnectCallback), ConnectedSocket);
return "";
}
catch (Exception e)
{
Console.WriteLine("CLIENT ERROR : \n" + e.ToString());
return "";
}
}
private void ConnectCallback(IAsyncResult ar)
{
try
{
Socket client = (Socket)ar.AsyncState;
client.EndConnect(ar);
Console.WriteLine("Client connected to server.");
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
public string SendMessageToServer(string text)
{
StartClient();
response = string.Empty;
text += "_|_!#*#_";
byte[] byteData = Encoding.UTF8.GetBytes(text);
ConnectedSocket.BeginSend(byteData, 0, byteData.Length, 0, new AsyncCallback(SendCallback), ConnectedSocket);
while(response.IndexOf("_|_!#*#_") == -1)
{
}
response = response.Replace("_|_!#*#_", "");
return response;
}
private void SendCallback(IAsyncResult ar)
{
try
{
Socket client = (Socket)ar.AsyncState;
int bytesSent = client.EndSend(ar);
StateObject state = new StateObject();
state.workSocket = client;
client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReceiveCallback), state);
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
private void ReceiveCallback(IAsyncResult ar)
{
try
{
StateObject state = (StateObject)ar.AsyncState;
Socket client = state.workSocket;
int bytesRead = client.EndReceive(ar);
if (bytesRead > 0)
{
state.sb.Append(Encoding.UTF8.GetString(state.buffer, 0, bytesRead));
response = state.sb.ToString();
if (response.IndexOf("_|_!#*#_") != -1)
{
state.sb.Clear();
return;
}
else
{
client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReceiveCallback), state);
}
}
else
{
if (state.sb.Length > 1)
{
response = state.sb.ToString();
}
client.EndReceive(ar);
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
public static byte[] StartClient(string ip, int port, byte[] message, bool needBack, out string errorMsg)
{
// Data buffer for incoming data.
byte[] bytes = new byte[1024];
// Connect to a remote device.
try
{
// Establish the remote endpoint for the socket.
IPAddress ipAddress = IPAddress.Parse(ip);
IPEndPoint remoteEP = new IPEndPoint(ipAddress, port);
// Create a TCP/IP socket.
Socket sender = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
// Connect the socket to the remote endpoint. Catch any errors.
try
{
sender.Connect(remoteEP);
// Send the data through the socket.
int bytesSent = sender.Send(message);
if (needBack)
{
// Receive the response from the remote device.
int bytesRec = sender.Receive(bytes);
byte[] array = new byte[bytesRec];
Array.Copy(bytes, array, bytesRec);
sender.Shutdown(SocketShutdown.Both);
sender.Close();
errorMsg = "";
return array;
}
else
{
errorMsg = "";
return null;
}
}
catch (ArgumentNullException ane)
{
errorMsg = string.Format("ArgumentNullException : {0}", ane.ToString());
return null;
}
catch (SocketException se)
{
errorMsg = string.Format("SocketException : {0}", se.ToString());
return null;
}
catch (Exception e)
{
errorMsg = string.Format("Unexpected exception : {0}", e.ToString());
return null;
}
}
catch (Exception e)
{
errorMsg = string.Format("Unexpected exception : {0}", e.ToString());
return null;
}
}
I use the code above to send and receive tcp message from the server.but I read nothing.
I don't want a async method.I have searched some example codes, they are written like this. Is there something wrong that I didn't realized.Thanks for help.
public class MyTcpClient
{
IPEndPoint _remote;
Socket _socket;
public bool IsStopReceive{set;get;}
public MyTcpClient(string ip, int port)
{
IPAddress ipAddress = IPAddress.Parse(ip);
_remote = new IPEndPoint(ipAddress, port);
_socket = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
_socket.Connect(_remote);
ThreadPool.QueueUserWorkItem(obj=>{
IsStopReceive = false;
ReceiveMsg();
});
}
public void Send(byte[] bytes) {
_socket.Send(bytes);
}
private MemoryStream memoryResult;
private void ReceiveMsg()
{
MemoryStream memStream = new MemoryStream();
while (!IsStopReceive)
{
byte[] bytes=new byte[1024];
int result = _socket.Receive(bytes);
if (result > 0) {
memStream.Write(bytes, 0, result);
}
else if (result == 0) {
IsStopReceive = true;
break;
}
}
if (OnMsgReceive != null) {
OnMsgReceive(memStream.GetBuffer());
}
}
public Action<byte[]> OnMsgReceive{set;get;}
}
the code above can receive the data.when I create a MyTcpClient instance,it will open a thread to receive data after connect to the target.
I use a Action to get the data after it finished.but this is async.Most important is that I don't know why I missed the data with the prev method.
I'm doing an application which require me as a client side to connect to a server and receive data from the server. I will need to do re-connection when the connection is disconnected. Below is my code:
public enum MySocketState
{
Disconnected = 0,
Connecting,
Connected
}
private Socket _serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
private byte[] _recieveBuffer = new byte[128];
void DataProcess()
{
try
{
if (_serverSocket == null || sockState == MySocketState.Disconnected)
{
Console.WriteLine("Trying to connect...");
SetupServer();
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
private void SetupServer()
{
try
{
_serverSocket.Connect("192.168.1.11", 1000);
}
catch (SocketException ex)
{
Console.WriteLine(ex.Message);
}
sockState = MySocketState.Connected;
Console.WriteLine("Server connected...");
_serverSocket.BeginReceive(_recieveBuffer, 0, _recieveBuffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), null);
}
private void ReceiveCallback(IAsyncResult AR)
{
try
{
if (_serverSocket == null)
_serverSocket = (Socket)AR.AsyncState;
int recieved = _serverSocket.EndReceive(AR);
if (recieved <= 0)
{
CloseSocket();
return;
}
byte[] recData = new byte[recieved];
Buffer.BlockCopy(_recieveBuffer, 0, recData, 0, recieved);
string strData = ASCIIEncoding.ASCII.GetString(recData);
Console.WriteLine(strData);
//Process the data stored in recData
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
CloseSocket();
}
finally
{
try
{
//Start receiving again
if (_serverSocket != null)
_serverSocket.BeginReceive(_recieveBuffer, 0, _recieveBuffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), null);
}
catch (Exception ex2)
{ }
}
}
public void CloseSocket()
{
try
{
if (_serverSocket != null)
{
if (_serverSocket.Connected)
_serverSocket.Shutdown(SocketShutdown.Both);
_serverSocket.Close();
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
_serverSocket = null;
sockState = MySocketState.Disconnected;
}
private void timer1_Tick(object sender, EventArgs e)
{
DataProcess();
}
I'm using a timer (timer1_tick) to always detect whether or not the server is connected.
But after it disconnected with the server, it cannot be reconnected back and below is the error message on line _serverSocket.Connect("192.168.1.11", 1000):
A first chance exception of type 'System.NullReferenceException' occurred in fform.exe
System.NullReferenceException: Object reference not set to an instance of an object.
at fform.Form1.SetupServer() in c:\Work\Project 2015\Form1.cs:line 143
at fform.Form1.DataProcess() in c:\Work\Project 2015\Form1.cs:line 79
Do you guys know how come it cannot be connect back?
Probably it's because you set _serverSocket to null after you CloseSocket() and did not create a new Socket instance when you try to reconnect.
public void CloseSocket()
{
...
_serverSocket = null;
...
}
Look at the line number in the error message
at fform.Form1.SetupServer() in c:\Work\Project 2015\Form1.cs:line
143 at fform.Form1.DataProcess() in c:\Work\Project
2015\Form1.cs:line 79
You should probably do the following when you reconnect:
private void SetupServer()
{
try
{
_serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //Added
_serverSocket.Connect("192.168.1.11", 1000);
}
...
}
I was doing Asynchronous Programming in c# when I came across this question,when the network is aborted.
My program can get a exception of ConnectionAborted almost 15 seconds after I send a invaild message from client to server.
My question is if I want to get the exception immediately after the network doesn't work,what need I do.
namespace _10_TCP模块化编程
{
class ObjectState
{
public Socket client;
public MyTcp obj;
public const int BufferSize = 256;
// Receive buffer.
public byte[] buffer = new byte[BufferSize];
// Received data string.
public StringBuilder sb = new StringBuilder();
}
class MyTcp
{
public delegate void dReceiver(object sender, string b);
public event dReceiver receive;
public Socket WebHabor;
//private bool connected;
public MyTcp(IPEndPoint iep, dReceiver dEventCall)
{
//接收消息的委托;
receive += dEventCall;
//创建socket连接;
WebHabor = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
ObjectState obs = new ObjectState();
obs.obj = this;
obs.client = WebHabor;
WebHabor.BeginConnect(iep, new AsyncCallback(ConnectCallback), obs);
//connected = WebHabor.Connected ? true : false;
Thread.Sleep(10);
if (WebHabor.Connected == true)
{
Receive();
}
else
{
Program.postLog("连接失败,请检查ip和port");
}
}
public static void ExceptionSolver(SocketException sep)
{
switch (sep.SocketErrorCode)
{
case SocketError.NotConnected:
//捕获ip地址输入错误的情况;
Program.postLog("不存在网络连接");
break;
case SocketError.ConnectionAborted:
//在这里处理频繁出现的错误,
//比如IP不对,网线没插
Program.postLog("连接中止");
break;
case SocketError.ConnectionRefused:
//远程主机正在主动拒绝连接;可能是连接的时候ip或port写错了;
Program.postLog("对方不接受连接,更可能是port的原因");
break;
case SocketError.HostUnreachable:
Program.postLog("连接目标不可达");
break;
case SocketError.TimedOut:
//尝试连接ip超时;
Program.postLog("尝试连接ip超时,更可能是ip的原因");
break;
default:
Program.postLog("捕获到" + sep.SocketErrorCode);
//这里直接报错,如果调试的时候出现这里的错误比较多,就移到上面解决,一般问题都是从来不出的
break;
}
}
public void Send(byte[] dataToSend,int byteCount)
{
try
{
WebHabor.BeginSend(dataToSend, 0, byteCount, 0, new AsyncCallback(SendCallback), WebHabor);
//System.Threading.Thread.Sleep(10);//为了让其它线程跑起来;
}
catch (SocketException sep)
{
Program.postLog("在Send这里");
ExceptionSolver(sep);
}
}
public void Receive()
{
byte[] buffer = new byte[256];
ObjectState obs = new ObjectState();
obs.obj = this;//这个传的是MyTcp;
obs.client = WebHabor;
try
{
WebHabor.BeginReceive(obs.buffer, 0, ObjectState.BufferSize, 0, new AsyncCallback(ReceiveCallback), obs);
}
catch (SocketException sep)
{
Program.postLog("在reveive这里");
ExceptionSolver(sep);
}
//receive.Invoke(this, buffer);
}
//beginConnect的回调函数;
private static void ConnectCallback(IAsyncResult ar)
{
ObjectState obs = (ObjectState)ar.AsyncState;
try
{
// Retrieve the socket from the state object.
Socket client = obs.client;
// Complete the connection.
client.EndConnect(ar);
//Console.WriteLine("Socket connected to {0}", client.RemoteEndPoint.ToString());
//连上就连上吧就不发数据了
//MessageBox.Show("Socket connected to " + client.RemoteEndPoint.ToString());
// Signal that the connection has been made.
//connectDone.Set();
}
catch (SocketException sep)
{
//Console.WriteLine(e.ToString());
//MessageBox.Show("connect回调函数出错了" + e.ToString());
/*********************************************************************
*
* 此处需要考察一下连接失败的异常情况。
*
*********************************************************************/
//obs.obj.connected = false;
Program.postLog("在ConnectCallback这里");
ExceptionSolver(sep);
}
}
private static void SendCallback(IAsyncResult ar)
{
try
{
// Retrieve the socket from the state object.
Socket client = (Socket)ar.AsyncState;
//System.Threading.Thread.Sleep(10);//为了让其它线程跑起来;
// Complete sending the data to the remote device.
int bytesSent = client.EndSend(ar);
Program.postLog("本次发送" + bytesSent + "个字节");
//Console.WriteLine("Sent {0} bytes to server.", bytesSent);
//MessageBox.Show("Sent " + bytesSent + " bytes to server.");
// Signal that all bytes have been sent.
//sendDone.Set();
}
catch (SocketException sep)
{
//MessageBox.Show("Send回调函数出错了" + e.ToString());
/*********************************************************************
*
* 此处需要考察一下发送失败的异常情况。
*
*********************************************************************/
Program.postLog("在SendCallback这里");
ExceptionSolver(sep);
}
}
private static void ReceiveCallback(IAsyncResult ar)
{
//byte[] buffer = new byte[256];
try
{
// Retrieve the state object and the client socket
// from the asynchronous state object.
//StateObject state = (StateObject)ar.AsyncState;
//Socket client = state.workSocket;
// Read data from the remote device.
ObjectState objs = (ObjectState)ar.AsyncState;
Socket client = objs.client;
int bytesRead = client.EndReceive(ar);
if (bytesRead > 0)
{
// There might be more data, so store the data received so far.
string getMsg = Encoding.ASCII.GetString(objs.buffer, 0, bytesRead);
//Console.WriteLine("新得到的数据是" + getMsg + "呵呵");
//MessageBox.Show("新得到的数据是" + getMsg);
string msg=Encoding.Default.GetString(objs.buffer, 0, bytesRead);
Program.postLog(msg);
//objs.obj.receive.Invoke(objs.obj, msg);//因为这是静态函数,这个objs.obj实际是MyTcp实例。
//MessageBox.Show(bytesRead.ToString() + "更新数据后:" + state.sb.ToString());
// Get the rest of the data.
client.BeginReceive(objs.buffer, 0, objs.buffer.Length, 0, new AsyncCallback(ReceiveCallback), objs);
}
else
{
//接到0字节说明对方主动断开了连接;
Program.postLog("对方主动断开连接");
}
}
catch (SocketException sep)
{
//MessageBox.Show("Receive回调函数出错了" + e.ToString());
/*********************************************************************
*
* 此处需要考察一下接收失败的异常情况。
*
*********************************************************************/
Program.postLog("在ReceiveCallback这里");
ExceptionSolver(sep);
}
}
}
}
I am not sure, but you can try using TcpClient.Client.Poll method as mentioned in one of the post.