socket_一个简单应用_源代码


 socket_一个简单应用_源代码

    代码文件有:
 outer.cpp outer.h
 socket.cpp socket.h
 sockmsg.cpp sockmsg.h
 linent.cpp service.cpp

outer.h:
=======

#ifndef _OUTER_H_
#define _OUTER_H_

// 数据类型定义
typedef unsigned char byte;

// 常量定义
// port
const int PORT    = 52309;
// 一个message的最大长度
const int MAX_MESSAGE_LEN = 512; 

const int BACKLOG   = 10;

const int CLOSE_TRY_TIMES = 10;

/*
 message types
 */
// get file list
const int GET_FILE_LIST  = 1;
// get dir list
const int GET_DIR_LIST  = 2;
// copy file
const int COPY_FILE   = 3;
// close socket
const int CLOSE_SOCKET  = 4;


/*
 patameter types
*/
//
const int TAG_DIR   = 21;

const int FILE_NAME   = 11;

const int TAG_FILE   = 12;

const int FILE_TEXT   = 13;


// function

void hexdump(byte *data, int len);

#endif

outer.cpp:
==========

#include <iostream>
#include "outer.h"

void hexdump(byte *data, int len) {
 int rows = len/16 + 1;

 for (int i=0; i<rows; i++) {
  if (i*16 >= len)
   break;
  int j;
  printf("%04x: ", rows << 4);
  for (j=0; (j<16)&&(i*16+j<len); j++) {
   printf("%02x ", data[i*16+j]);
   if (j == 7)
    printf("- ");
  }
  printf("| ");
  for (j=0; (j<16)&&(i*16+j<len); j++) {
   if (isprint(data[i*16+j]))
    printf("%c", data[i*16+j]);
   else
    printf(".");
  }  
  printf("/n");
 }
}

socket.h:
=========
/**
 * $Id: Socket.h,v 1.3 2005/04/06 07:16:14 guest Exp $
 */

#include <string>
#include "outer.h"

#ifndef __SOCKET_H__
#define __SOCKET_H__

using std::string;

class Socket {
public:

    /**
     * Creates an unconnected socket, with the system-default
     * type of SocketImpl.
     */
    Socket();

    /**
     * Creates a stream socket and connects it to the specified
     * port number on the named host.
     */
    Socket(string host, int port);

    /**
     * Destructor
     */
    virtual ~Socket();

 /**
     * Creates an unconnected socket, with the system-default
     * type of SocketImpl.
     */
 bool setup();

    /**
     * Closes this socket.
     */
    void close();
 
 /**
     * Closes this socket.
     */
 void close(int fd);

    /**
     * Connects this socket to the server.
     */
    bool connect(string host, int port);

 /**
  * Listen witch this socket.
  */
 bool listen();

 /**
  *
  */
 int accept();

    /**
     * Returns the address to which the socket is connected.
     */
    string getInetAddress();

    /**
     * Gets the local address to which the socket is bound.
     */
    string getLocalAddress();

    /**
     * Returns the local port to which this socket is bound.
     */
    int getLocalPort();

    /**
     * Returns the remote port to which this socket is connected.
     */
    int getPort();

    /**
     * Returns the closed state of the socket.
     */
    bool isClosed();

    /**
     * Returns the connection state of the socket.
     */
    bool isConnected();

    /**
     * Receives a message from this socket.
     */
    int recv(byte *buf, int len);

 /**
     * Receives a message from this socket.
     */
    int recv(int new_fd, byte *buf, int len);

    /**
     * Sends a message through this socket.
     */
    int send(const byte *msg, int len);

 /**
     * Sends a message through this socket.
     */
    int send(int new_fd, const byte *msg, int len);

private:
    int _fd;
    bool _connected;
    bool _closed;
};

#endif

socket.cpp:
===========
/**
 * $Id: Socket.cpp,v 1.5 2005/04/06 07:16:14 guest Exp $
 */

#include <errno.h>
#include <stdio.h>
#include <winsock2.h>

#include "Socket.h"
#include "outer.h"

/**
 * Creates an unconnected socket, with the system-default
 * type of SocketImpl.
 */
Socket::Socket() {

 setup();

    _closed = false;
}

/**
 * Creates a stream socket and connects it to the specified
 * port number on the named host.
 */
Socket::Socket(string host, int port) {
    setup();
    connect(host, port);
}

/**
 * Creates an unconnected socket, with the system-default
 * type of SocketImpl.
 */
bool Socket::setup() {

 WSADATA wsd;
 _fd = WSAStartup(MAKEWORD(2,2), &wsd); 
 if(_fd) {
  printf("WSAStartup function err!/n");
  return false;
 }
 
    _connected = false;
    _closed = true;
 printf("Socket: WSAStartup success execute./n");

    _fd = ::socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
    if (_fd == -1) {
  printf(strerror(errno));
  return false;
    }
 printf("Socket: socket success execute./n");
 return true;
}

/**
 * Destructor
 */
Socket::~Socket() {
    close();
}

/**
 * Closes this socket.
 */
void Socket::close() {
    if (!isClosed()) {
        if (_connected) {
            printf("Socket: Close connection to /"%s:%d/"/n",
                getInetAddress().c_str(), getPort());
        }

  int trytimes = 0;
        while(::closesocket(_fd) && trytimes < CLOSE_TRY_TIMES)
   trytimes++;
  
  if(trytimes == 10) {
   printf("Cannot close socket!/n");
  }
  else {
   _closed = true;
  }
    }
}

/**
 * Closes this socket.
 */
void Socket::close(int fd) {
    if (!isClosed()) {
        if (_connected) {
            printf("Socket: Close connection to /"%s:%d/"/n",
                getInetAddress().c_str(), getPort());
        }

  int trytimes = 0;
        while(::closesocket(fd) && trytimes < CLOSE_TRY_TIMES)
   trytimes++;
  
  if(trytimes == 10) {
   printf("Cannot close socket!/n");
  }
  else {
   _closed = true;
  }
    }
}

/**
 * Connects this socket to the server.
 */
bool Socket::connect(string host, int port) {
    struct hostent *_h = gethostbyname(host.c_str());
    if (_h == 0) {
  printf(strerror(h_errno));
  return false;
    }

    struct in_addr *_addr = (struct in_addr *)_h->h_addr;
    struct sockaddr_in sin;
    sin.sin_family = AF_INET;
    sin.sin_addr = *_addr;
    sin.sin_port = htons(port);

 if (::connect(_fd, (sockaddr *)&sin, sizeof(sin)) == SOCKET_ERROR) {
  printf(strerror(errno));
  return false;
 }

    printf("Socket: Establish the connection to /"%s:%d/"/n",
        getInetAddress().c_str(), getPort());

    _connected = true;
 return true;
}

/**
 * Listen witch this socket.
 */
bool Socket::listen()
{
 struct sockaddr_in my_addr;
 
 my_addr.sin_family = AF_INET;
 my_addr.sin_port = htons(PORT);
 my_addr.sin_addr.s_addr = INADDR_ANY;
 
 if(::bind(_fd, (struct sockaddr *)&my_addr, sizeof(struct sockaddr)) == SOCKET_ERROR)
 {
  printf(strerror(errno));
  return false;
 }
 else
  printf("bind ok!/n");

 if(::listen(_fd, BACKLOG) == SOCKET_ERROR)
 {
  printf(strerror(errno));
  return false;
 }
 else
  printf("listen ok!/n");

 return true;
}

/**
 *
 */
int Socket::accept()
{
 int new_fd;
 struct sockaddr_in their_addr;
 int sin_size = sizeof(their_addr);
 
 printf("accepting... /n");

 new_fd = ::accept(_fd,
     (struct sockaddr *)&their_addr,
     &sin_size);
 return new_fd == SOCKET_ERROR ? -1:new_fd;
}

/**
 * Returns the address to which the socket is connected.
 */
string Socket::getInetAddress() {
    struct sockaddr_in sin;
    //socklen_t socklen = sizeof(sin);
 int socklen = sizeof(sin);
    if (getpeername(_fd, (struct sockaddr *)&sin, &socklen) == -1) {
        printf(strerror(errno));
  return NULL;
    }

    return inet_ntoa(sin.sin_addr);
}

/**
 * Gets the local address to which the socket is bound.
 */
string Socket::getLocalAddress() {
    struct sockaddr_in sin;
    //socklen_t socklen = sizeof(sin);
 int socklen = sizeof(sin);
    if (getsockname(_fd, (struct sockaddr *)&sin, &socklen) == -1) {
        printf(strerror(errno));
  return NULL;
    }

    return inet_ntoa(sin.sin_addr);
}

/**
 * Returns the local port to which this socket is bound.
 */
int Socket::getLocalPort() {
    struct sockaddr_in sin;
    //socklen_t socklen = sizeof(sin);
 int socklen = sizeof(sin);
    if (getsockname(_fd, (struct sockaddr *)&sin, &socklen) == -1) {
        printf(strerror(errno));
  return -1;
    }

    return ntohs(sin.sin_port);
}

/**
 * Returns the remote port to which this socket is connected.
 */
int Socket::getPort() {
    struct sockaddr_in sin;
    //socklen_t socklen = sizeof(sin);
 int socklen = sizeof(sin);
    if (getpeername(_fd, (struct sockaddr *)&sin, &socklen) == -1) {
        printf(strerror(errno));
  return NULL;
    }

    return ntohs(sin.sin_port);
}

/**
 * Returns the closed state of the socket.
 */
bool Socket::isClosed() {
    return _closed;
}

/**
 * Returns the connection state of the socket.
 */
bool Socket::isConnected() {
    return _connected;
}

/**
 * Receives a message from this socket.
 */
int Socket::recv(int new_fd, byte *buf, int len)
{
 int nb = ::recv(new_fd, (char *)buf, len, 0);
    if (nb == -1) {
  printf("Error! recv./n");
    }

    return nb;
}

/**
 * Receives a message from this socket.
 */
int Socket::recv(byte *buf, int len) {
    return recv(_fd, buf, len);
}

/**
 * Sends a message through this socket.
 */
int Socket::send(const byte *msg, int len) {
    return send(_fd, msg, len);
}

/**
 * Sends a message through this socket.
 */
int Socket::send(int new_fd, const byte *msg, int len)
{
 int nb = ::send(new_fd, (char *)msg, len, 0);
    if (nb == -1) {
        //throw SocketException(strerror(errno));
  printf("Error! send./n");
    }

    return nb;
}

sockmsg.h
==========

//
//  A message object.
//
// filename:SockMsg.h
// struct:
//  Message
//   +- Protocol Version  1 byte
//   +- Message type   2 bytes
//   +- Message Length  2 bytes
//   for ()
//    +- Patameter type   2 bytes
//    +- Patameter tag   1 bytes
//    +- Patameter index   2 bytes
//    +- Patameter data length 2 bytes
//    +- Patameter data   var
//
//

#if !defined(_SOCKMSG_H_)
#define _SOCKMSG_H_

#include "outer.h"

class MsgPatameter
{
public:
 MsgPatameter(byte *data, int len) {
  _data = new byte[len];
  memcpy(_data, data, len);
 }

 ~MsgPatameter(){delete[] _data;}

 inline int getType() const {return _data[0] << 8 | _data[1];}
 inline int getTag() const {return _data[2];}
 inline int getIndex() const {return _data[3] << 8 | _data[4];}
 inline int getLen() const {return _data[5] << 8 | _data[6];}

 byte *getData() const {return _data+7;}
private:
 byte *_data;
};

class SockMsg 
{
public:
 /**
  *
  */
 SockMsg(void);

 /**
  *
  */
 virtual ~SockMsg(void);

public:
 /**
     * Returns the version of the protocol used
     * by this message object.
     */
 int getProtocolVersion(void) const;
 
 /**
  * Returns the message length.
  */
 int getMessageLength(void) const;

 /**
  * Returns the message length.
  */
 int Length(void) const;

 /**
  * Returns the type of this message object.
  */
 int getMessageType(void) const;

 /**
  * Sets the version of the protocol used.
  */
 void setProtocolVersion(const int &version);

 /**
     * Sets the type of this message object.
     */
    void setMessageType(const int &type);

 /**
  * Sets a patameter info in the message.
  */
 void setPatameter(int type, char tag, int index, int len, const byte *data);

 /**
  * Sets a patameter info in the message.
  */
 void setPatameter(int type, int len, const byte *data);

 /**
  * Sets a patameter info in the message.
  */
 void setPatameter(int type);

 /**
  * Clear patameters from in the message.
  */
 void clearPatameter(void);

 /**
  * Gets data of the message.
  */
 byte *getData(void);

 /**
  * 
  */
 MsgPatameter * getPatameter(const int &index) const;

 /**
  * Print datas of this message object.
  */
 void toString(void) const;

private:
    /**
     * Sets the message_length field.
     */
    void setMessageLength(const int &length);


private:
 byte *_data;

 // MsgPatameter

};

#endif // !defined(_SOCKMSG_H_)

sockmsg.cpp:
============
// SockMsg.cpp: implementation of the SockMsg class.
//
//

#include <iostream>
#include "SockMsg.h"

//
// Construction/Destruction
//

SockMsg::SockMsg(void)
{
 _data = new byte[MAX_MESSAGE_LEN];

 memset(_data, 0, MAX_MESSAGE_LEN);

 setProtocolVersion(1);
 setMessageType(0);
 setMessageLength(0);
}

SockMsg::~SockMsg(void)
{
 delete[] _data;
}

/**
 * Returns the version of the protocol used
 * by this _message object.
 */
int SockMsg::getProtocolVersion(void) const {
    return _data[0];
}

/**
 * Returns the _message_length field.
 */
int SockMsg::getMessageLength(void) const {
    return (_data[3] << 8) | _data[4];
}

/**
 * Returns the message length.
 */
int SockMsg::Length(void) const {
 return getMessageLength() + 5;
}

/**
 * Returns the type of this message object.
 */
int SockMsg::getMessageType(void) const {
    return (_data[1] << 8) | _data[2];
}

/**
 * Sets the version of the protocol used.
 */
void SockMsg::setProtocolVersion(const int &version) {
    _data[0] = version;
}

/**
 * Sets the message length.
 */
void SockMsg::setMessageLength(const int &length) {
    _data[3] = length >> 8;
    _data[4] = length;
}

/**
 * Sets the type of this message object.
 */
void SockMsg::setMessageType(const int &type) {
    _data[1] = type >> 8;
    _data[2] = type;
}

/**
 * Sets a patameter info in the message.
 */
void SockMsg::setPatameter(int type, int len, const byte *data) {
 setPatameter(type, 1, 0, len, data);
}

/**
 * Sets a patameter info in the message.
 */
void SockMsg::setPatameter(int type) {
 setPatameter(type, 1, 0, 0, NULL);
}

/**
 * Sets a patameter info in the message.
 */
void SockMsg::setPatameter(int type, char tag, int index, int len, const byte *data) {
 int len_ = getMessageLength() + 5;

 _data[len_]  = type >> 8;
 _data[len_ + 1] = type;

 _data[len_ + 2] = tag;

 _data[len_ + 3] = index >> 8;
 _data[len_ + 4] = index;

 _data[len_ + 5] = len >> 8;
 _data[len_ + 6] = len;

 if (data)
  memcpy(&_data[len_ + 7], data, len);

 setMessageLength(len_ + len + 2);
}

/**
 * Gets data of the message.
 */
byte *SockMsg::getData(void) {
 return _data;
}

/**
 * Clear patameters from in the message.
 */
void SockMsg::clearPatameter(void) {
 setMessageLength(0);
}

/**
 * 
 */
MsgPatameter *SockMsg::getPatameter(const int &index) const{
 int patameters_ = 5;
 int len_ = getMessageLength();
 int index_ = 0, patlen_;

 while (len_ - patameters_ >0) {
  patlen_ = _data[patameters_ + 5] << 8 | _data[patameters_ + 6];

  if (index_ == index) {
   MsgPatameter *patameter = new MsgPatameter(_data + patameters_, patlen_

+ 7);
   return patameter;
  }
  patameters_ += patlen_ + 7;
  index_++;
 }
 return NULL;
}

/**
 * Print datas of this message object.
 */
void SockMsg::toString(void) const {
 int patameters_ = 5;
 int len_ = getMessageLength();

 printf("Message info :/n");
 printf("  message protocol : %d/n", getProtocolVersion());
 printf("  message type  : %d/n", getMessageType());
 printf("  message length : %d/n", getMessageLength());
 printf("  message patameter :/n");

 MsgPatameter *p_pata = NULL;
 for (int i=0; ; i++) {
  p_pata = getPatameter(i);
  if (!p_pata)
   break;

  printf("    patameter type      : %d/n", p_pata->getType());
  printf("    patameter tag       : %d/n", p_pata->getTag());
  printf("    patameter index     : %d/n", p_pata->getIndex());
  printf("    patameter data len  : %d/n", p_pata->getLen());

  hexdump(p_pata->getData(), p_pata->getLen());

  delete p_pata;
  p_pata = NULL;
 }
}

client.cpp
==========

#include <stdio.h>
#include <Socket.h>
#include <SockMsg.h>
#include <string.h>
#include <iostream>

using std::cin;

int main(int argc,  char **argv)
{
 printf("socket of client is run .../n");

 Socket s;
 SockMsg msg;

 if(!s.connect("dezhi", PORT)) {
  printf("Not service!/n");
  return 0;
 }

 while (1) {
  printf("select opration. f(show file list), c(copy file), q(exit)./n");
  char m;
  cin >> m;
  if (m == 'q')
   break;

  if (m == 'f') {
   printf("select dir :");
   char *dir = new char[64];
   cin >> dir;
   
   msg.setMessageType(GET_FILE_LIST);
   msg.setPatameter(TAG_DIR, strlen(dir), (byte *)dir);
  }
  else if (m == 'c') {
   printf("select file : ");
   char *file = new char[64];
   cin >> file;
   
   msg.setMessageType(COPY_FILE);
   msg.setPatameter(TAG_FILE, strlen(file)+1, (byte *)file);
  }
  else {
   printf("No operation !/n");
   continue;
  }

  s.send(msg.getData(), msg.Length());
  s.recv(msg.getData(), 512);
  msg.toString();
 }

 msg.clearPatameter();
 msg.setMessageType(CLOSE_SOCKET);
 s.send(msg.getData(), msg.Length());
 
 s.close();
 
 return 0;
}

service.cpp:
============
#include <stdio.h>
#include <Socket.h>
#include <SockMsg.h>
#include <string.h>
#include <iostream>

int main(int argc,  char **argv)
{
 printf("socket of service is run .../n");

 Socket s;
 s.listen();
 SockMsg msg;

 while (1) {
  int new_fd = s.accept();

  while (s.recv(new_fd, msg.getData(), 512) != -1) {
   msg.toString();
   
   if (msg.getMessageType() == CLOSE_SOCKET)
    break;
   MsgPatameter *p_pata = msg.getPatameter(0);
   if (msg.getMessageType() == GET_FILE_LIST) {
    
    if (p_pata->getType() == TAG_DIR) {
     char *dir = (char *)p_pata->getData();

     getfilelist(dir);
    }
    msg.clearPatameter();

    c_file *cf = _v.begin();
    for (; cf < _v.end(); cf++) {
     char *va = cf->getdata();
     printf("va len = %d/n", strlen(va));
     msg.setPatameter(FILE_NAME, strlen(va), (byte *)va);
    }
   }
   else if (msg.getMessageType() == COPY_FILE) {
    if (p_pata->getType() == TAG_FILE) {
     int len = p_pata->getLen();
     char *file = (char *)p_pata->getData();
     
     msg.clearPatameter();
     FILE *f_ = fopen(file, "r");
     if (!f_)
      break;
     byte *buf = new byte[128];
     fread(buf, 128, 1, f_);
     msg.setPatameter(FILE_TEXT, 128, buf);
     
    }
    
   }
   delete p_pata;
   msg.toString();
   s.send(new_fd, msg.getData(), msg.Length());
   
  }
  s.close(new_fd);
 }
 s.close();

 return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
首先要理解基本的原理,2台电脑间实现TCP通讯,首先要建立起连接,在这里要提到服务器端与客户端,两个的区别通俗讲就是主动与被动的关系,两个人对话,肯定是先有人先发起会话,要不然谁都不讲,谈什么话题,呵呵!一样,TCPIP下建立连接首先要有一个服务器,它是被动的,它只能等待别人跟它建立连接,自己不会去主动连接,那客户端如何去连接它呢,这里提到2个东西,IP地址和端口号,通俗来讲就是你去拜访某人,知道了他的地址是一号大街2号楼,这个是IP地址,那么1号楼这么多门牌号怎么区分,嗯!门牌号就是端口(这里提到一点,我们访问网页的时候也是IP地址和端口号,IE默认的端口号是80),一个服务器可以接受多个客户端的连接,但是一个客户端只能连接一台服务器,在连接后,服务器自动划分内存区域以分配各个客户端的通讯,那么,那么多的客户端服务器如何区分,你可能会说,根据IP么,不是很完整,很简单的例子,你一台计算机开3个QQ,服务器怎么区分?所以准确的说是IP和端口号,但是客户端的端口号不是由你自己定的,是由计算机自动分配的,要不然就出现端口冲突了,说的这么多,看下面的这张图就简单明了了。 在上面这张图中,你可以理解为程序A和程序B是2个SOCKET程序,服务器端程序A设置端口为81,已接受到3个客户端的连接,计算机C开了2个程序,分别连接到E和D,而他的端口是计算机自动分配的,连接到E的端口为789,连接到D的为790。 了解了TCPIP通讯的基本结构后,接下来讲解建立的流程,首先声明一下我用的开发环境是Visual Studio2008版的,语言C#,组件System.Net.Sockets,流程的建立包括服务器端的建立和客户端的建立,如图所示: 二、实现: 1.客户端: 第一步,要创建一个客户端对象TcpClient(命名空间在System.Net.Sockets),接着,调用对象下的方法BeginConnect进行尝试连接,入口参数有4个,address(目标IP地址),port(目标端口号),requestCallback(连接成功后的返调函数),state(传递参数,是一个对象,随便什么都行,我建议是将TcpClient自己传递过去),调用完毕这个函数,系统将进行尝试连接服务器。 第二步,在第一步讲过一个入口参数requestCallback(连接成功后的返调函数),比如我们定义一个函数void Connected(IAsyncResult result),在连接服务器成功后,系统会调用此函数,在函数里,我们要获取到系统分配的数据流传输对象(NetworkStream),这个对象是用来处理客户端与服务器端数据传输的,此对象由TcpClient获得,在第一步讲过入口参数state,如果我们传递了TcpClient进去,那么,在函数里我们可以根据入口参数state获得,将其进行强制转换TcpClient tcpclt = (TcpClient)result.AsyncState,接着获取数据流传输对象NetworkStream ns = tcpclt.GetStream(),此对象我建议弄成全局变量,以便于其他函数调用,接着我们将挂起数据接收等待,调用ns下的方法BeginRead,入口参数有5个,buff(数据缓冲),offset(缓冲起始序号),size(缓冲长度),callback(接收到数据后的返调函数),state(传递参数,一样,随便什么都可以,建议将buff传递过去),调用完毕函数后,就可以进行数据接收等待了,在这里因为已经创建了NetworkStream对象,所以也可以进行向服务器发送数据的操作了,调用ns下的方法Write就可以向服务器发送数据了,入口参数3个,buff(数据缓冲),offset(缓冲起始序号),size(缓冲长度)。 第三步,在第二步讲过调用了BeginRead函数时的一个入口参数callback(接收到数据后的返调函数),比如我们定义了一个函数void DataRec(IAsyncResult result),在服务器向客户端发送数据后,系统会调用此函数,在函数里我们要获得数据流(byte数组),在上一步讲解BeginRead函数的时候还有一个入口参数state,如果我们传递了buff进去,那么,在这里我们要强制转换成byte[]类型byte[] data= (byte[])result.AsyncState,转换完毕后,我们还要获取缓冲区的大小int length = ns.EndRead(result),ns为上一步创建的NetworkStream全局对象,接着我们就可以对数据进行处理了,如果获取的length为0表示客户端已经断开连接。 具体实现代码,在这里我建立了一个名称为Test的类: 2.服务器端: 相对于客户端的实现,服务器端的实现稍复杂一点,因为前面讲过,一个服务器端可以接受N个客户端的连接,因此,在服务器端,有必要对每个连接上来的客户端进行登记,因此服务器端的程序结构包括了2个程序结构,第一个程序结构主要负责启动服务器、对来访的客户端进行登记和撤销,因此我们需要建立2个类。 第一个程序结构负责服务器的启动与客户端连接的登记,首先建立TcpListener网络侦听类,建立的时候构造函数分别包括localaddr和port2个参数,localaddr指的是本地地址,也就是服务器的IP地址,有人会问为什么它自己不去自动获得本机的地址?关于这个举个很简单的例子,服务器安装了2个网卡,也就有了2个IP地址,那建立服务器的时候就可以选择侦听的使用的是哪个网络端口了,不过一般的电脑只有一个网络端口,你可以懒点直接写个固定的函数直接获取IP地址System.Net.Dns.GetHostAddresses(System.Net.Dns.GetHostName())[0],GetHostAddresses函数就是获取本机的IP地址,默认选择第一个端口于是后面加个[0],第2个参数port是真侦听的端口,这个简单,自己决定,如果出现端口冲突,函数自己会提醒错误的。第二步,启动服务器,TcpListener.Start()。第三步,启动客户端的尝试连接,TcpListener.BeginAcceptTcpClient,入口2个参数,callback(客户端连接上后的返调函数),state(传递参数,跟第二节介绍的一样,随便什么都可以,建立把TcpListener自身传递过去),第四步,建立客户端连接上来后的返调函数,比如我们建立个名为void ClientAccept(IAsyncResult result)的函数,函数里,我们要获取客户端的对象,第三步里讲过我们传递TcpListener参数进去,在这里,我们通过入口参数获取它TcpListener tcplst = (TcpListener)result.AsyncState,获取客户端对象TcpClient bak_tcpclient = tcplst.EndAcceptTcpClient(result),这个bak_tcpclient我建议在类里面建立个列表,然后把它加进去,因为下一个客户端连接上来后此对象就会被冲刷掉了,客户端处理完毕后,接下来我们要启动下一个客户端的连接tcplst.BeginAcceptTcpClient(new AsyncCallback(sub_ClientAccept), tcplst),这个和第三步是一样的,我就不重复了。 第二个程序结构主要负责单个客户端与服务器端的处理程序,主要负责数据的通讯,方法很类似客户端的代码,基本大同,除了不需要启动连接的函数,因此这个程序结构主要启动下数据的侦听的功能、判断断开的功能、数据发送的功能即可,在第一个程序第四步我们获取了客户端的对象bak_tcpclient,在这里,我们首先启动数据侦听功能NetworkStream ns= bak_tcpclient.GetStream();ns.BeginRead(data, 0, 1024, new AsyncCallback(DataRec), data);这个跟我在第二节里介绍的是一模一样的(第二节第10行),还有数据的处理函数,数据发送函数,判断连接已断开的代码与第二节也是一模一样的,不过在这里我们需要额外的添加一段代码,当判断出连接已断开的时候,我们要将客户端告知第一个程序结构进行删除客户端操作,这个方法我的实现方法是在建立第二个程序结构的时候,将第一个程序结构当参数传递进来,判断连接断开后,调用第一个程序结构的公开方法去删除,即从客户端列表下删除此对象。 第一个程序结构我们定义一个TSever的类,第二个程序结构我们一个TClient的类,代码如下:TSever类
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值