星期四, 7月 06, 2006

Socket with C

開個socket 就要 "include winsock2.h" 才有會個特異功能,這很正常的杯.
java 就要 import java.net.

而C的funtion裡面常有的縮寫
AF PF
PF -> protocaol family
其實沒啥差別

SOCK_STREAM
SOCK_DGRAM
SOCK_RAW <--特別的方式可以聽到IP層的資料.如icmp
有趣的是socket(int,int,int)都可以是int型態.也就是給數字也通的樣子.

socket_in 是寫一些網路資訊的資料結構

可以利用bind 和 connect 的funtion去把socket和這些資料連接
bind 結合參數 <-多用於server
connect是連線 <-多用於client
listen(socket , int) <--當完成 bind 後就可以利用來等連線 ,後面的int為連線數
accept(socket,sockaddr,int) 接受連線 <--準備傳資料啦.當後面兩個arg都為 null的時候表示不介意連線的點為何.
最後到了傳送的部份是send 和 recv .
當然還有UDP用的recvfrom 和 sendto.<-UDP要對方位置

架構概念 和java有點不一樣
socket -> bind -> listen -> accept -> recv && send
sockaddr_in sockaddr_in

下面是這次寫的小範例,不過在檔案部份小懶惰,沒寫好,所以有要copy得人要小心一點
//------------------------------------------------------------------------//
#include
#include
#include
#include "winsock2.h"
#pragma comment(lib,"ws2_32")
using namespace std;
void main() {

char readc[100000];
ifstream inFile("aaa.cmp", ios::binary);
ofstream out("bbb.txt",ios::binary);
long nFileSize= inFile.tellg();




// Initialize Winsock.
WSADATA wsaData;
int iResult = WSAStartup( MAKEWORD(2,2), &wsaData );
if ( iResult != NO_ERROR )
printf("Error at WSAStartup()\n");
//-------------初始化 winsock很重要...沒有就不會動了
// Create a socket.
SOCKET m_socket;
m_socket = socket( AF_INET, SOCK_STREAM, IPPROTO_TCP );

if ( m_socket == INVALID_SOCKET ) {
printf( "Error at socket(): %ld\n", WSAGetLastError() );
WSACleanup();
return;
}

// Bind the socket.
sockaddr_in service;
service.sin_family = AF_INET;
service.sin_addr.s_addr = inet_addr( "127.0.0.1" );
service.sin_port = htons( 27015 );


if ( bind( m_socket, (SOCKADDR*) &service, sizeof(service) ) == SOCKET_ERROR ) {
printf( "bind() failed.\n" );
closesocket(m_socket);
return;
}

// Listen on the socket.
if ( listen( m_socket, 1 ) == SOCKET_ERROR )
printf( "Error listening on socket.\n");

// Accept connections.
SOCKET AcceptSocket;

printf( "Waiting for a client to connect...\n" );

int bytesSent=SOCKET_ERROR;
while (1) {
AcceptSocket = SOCKET_ERROR;

while ( AcceptSocket == SOCKET_ERROR ) {
AcceptSocket = accept( m_socket, NULL, NULL );
}

printf( "Client Connected.\n");
m_socket = AcceptSocket;
break;
}

// Send and receive data.


while(inFile)
{
inFile.read(readc,100000);
bytesSent = send( m_socket, readc, 100000, 0 );
}

out.close();
inFile.close();



closesocket(m_socket);


}

沒有留言: