vvv123's Blog

Happy coding

[iphone][api][network]Socket使用

閒話...

最近回歸程式員,發現硬體設計可能不太適合我。發現程式員也許最辛苦的就是找如何使用api。在此提供sample code for socket.

introduction...

client端使用iphone, server端使用java。

Server端會計數client連了幾次,並回傳次數給client端。

 

Code...

client....

#import <CoreFoundation/CoreFoundation.h>

#include <sys/types.h>

#include <sys/time.h>

#include <sys/socket.h>

#include <netinet/in.h>

#include <netdb.h>

#import <CoreFoundation/CFSocket.h>

 

void dealWithData(CFSocketRef s, CFSocketCallBackType type, CFDataRef 

  address, const void *data, void *info)

{

/*

printf("received %d bytes from socket %d\n", 

  CFDataGetLength((CFDataRef)data), CFSocketGetNative(s));

 

*/

UInt8 buffer[100];

CFDataGetBytes((CFDataRef)data, CFRangeMake(0,CFDataGetLength((CFDataRef)data)),buffer);

 

 

printf("%s\n",(char*)buffer);

}

 

main ()

{

CFSocketRef s = CFSocketCreate(NULL, PF_INET, SOCK_STREAM, IPPROTO_TCP

  kCFSocketDataCallBack, dealWithData, NULL);

CFDataRef address, data;

struct sockaddr_in sin;

char message[] = "Insert message to send here.\n";

CFRunLoopSourceRef source;

 

memset(&sin, 0, sizeof(sin));

sin.sin_family = AF_INET;

sin.sin_port = htons(8880);

 

address = CFDataCreate(NULL, (char *)&sin, sizeof(sin));

data = CFDataCreate(NULL, message, sizeof(message));

CFSocketConnectToAddress(s, address, 0);

CFSocketSendData(s, NULL, data, 0);

CFRelease(address);

CFRelease(data);

 

source = CFSocketCreateRunLoopSource(NULL, s, 0);

CFRunLoopAddSource(CFRunLoopGetCurrent(), source, kCFRunLoopDefaultMode);

CFRelease(source);

CFRelease(s);

CFRunLoopRun();

}

 

 

Server...

 

 

import java.io.*;

 

import java.net.Socket;

 

public class Servertest1_client{

public static int count = 0;

public void startCount(){

while(true){

try{

Socket socket = new Socket("localhost",8880);

 

socket.close();

}catch(IOException e){

System.out.println("Some error!!\n");

}

}

}

public static void main(String [] args){

Servertest1_client st = new Servertest1_client();

st.startCount();

}

}