我尝试做的是使用套接字将目标C(GCDAsyncSocket)的数据(以json格式)发送到服务器C#。
基本上,下面的代码适用于C#服务器和客户端目标C.
public class SynchronousSocketClient {
public static void StartClient() {
// Data buffer for incoming data.
byte[] bytes = new byte[1024];
// Connect to a remote device.
try {
// Establish the remote endpoint for the socket.
// This example uses port 11000 on the local computer.
IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName())
IPAddress ipAddress = ipHostInfo.AddressList[0];
IPEndPoint remoteEP = new IPEndPoint(ipAddress,11000);
// 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);
Console.WriteLine("Socket connected to {0}",
sender.RemoteEndPoint.ToString());
// Encode the data string into a byte array.
byte[] msg = Encoding.ASCII.GetBytes("This is a test<EOF>");
// Send the data through the socket.
int bytesSent = sender.Send(msg);
// Receive the response from the remote device.
int bytesRec = sender.Receive(bytes);
Console.WriteLine("Echoed test = {0}",
Encoding.ASCII.GetString(bytes,0,bytesRec));
// Release the socket.
sender.Shutdown(SocketShutdown.Both);
sender.Close();
} catch (ArgumentNullException ane) {
Console.WriteLine("ArgumentNullException : {0}",ane.ToString());
} catch (SocketException se) {
Console.WriteLine("SocketException : {0}",se.ToString());
} catch (Exception e) {
Console.WriteLine("Unexpected exception : {0}", e.ToString());
}
} catch (Exception e) {
Console.WriteLine( e.ToString());
}
}
public static int Main(String[] args) {
StartClient();
return 0;
}
}
- (void)connect:(NSString *)host portNo:(NSString *)portno {
m_host = host ;
m_portno = [portno intValue];
if (m_soc == nil) {
m_soc = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()];
} else {
if (m_soc.isConnected) {
[m_soc disconnect];
}
}
NSError *error = nil;
m_isConnected = false ;
if (![m_soc connectToHost:m_host onPort:m_portno withTimeout:3.0 error:&error]) {
[self onError:@"Error in Connecting to Host."];
}
}
不幸的是,我得到的结果是
&#34;错误的NSError *域:@&#34; GCDAsyncSocketErrorDomain&#34; - 代码:3&#34;
这只是一个连接,尚未对发送数据做任何事情。 希望得到大家的回应。非常感谢。