tcp 数据传输实例测试

本文提供了一个使用VC++和Java实现的TCP客户端-服务器通信示例,演示了一次连接后持续发送数据的过程。VC++部分使用Winsock库进行网络编程,而Java部分则利用标准库完成网络交互。
 
  1. #include <Winsock2.h>
  2. #include <stdio.h>
  3. void main()
  4. {
  5.     WORD wVersionRequested;
  6.     WSADATA wsaData;
  7.     int err;
  8.     wVersionRequested = MAKEWORD( 2, 2 );
  9.     err = WSAStartup( wVersionRequested,&wsaData);
  10.     if( err != 0){
  11.         return;
  12.     }
  13.     if( LOBYTE( wsaData.wVersion)!= 2||
  14.         HIBYTE(wsaData.wVersion)!= 2)
  15.     {
  16.         WSACleanup();
  17.         return;
  18.     }
  19.     //SOCKET    sockClient = socket(AF_INET,SOCK_STREAM,0);
  20.     SOCKADDR_IN addrSrv;
  21.     addrSrv.sin_addr.S_un.S_addr = inet_addr("10.150.20.45");
  22.     addrSrv.sin_family = AF_INET;
  23.     addrSrv.sin_port = htons(6000);
  24.     SOCKET  sockClient;
  25.         
  26.                 sockClient = socket(AF_INET,SOCK_STREAM,0);
  27.         connect(sockClient,(SOCKADDR*)&addrSrv,sizeof(SOCKADDR));
  28.     for(int i=0;i<30;i++)
  29.     {
  30.         //char recvBuf[100];
  31.         //recv(sockClient,recvBuf,100,0);
  32.         //printf("%s/n",recvBuf);
  33.         try{
  34.             
  35.             send(sockClient,"This",strlen("This"),0);
  36.         }catch(...)
  37.         {
  38.             printf("%s/n","Errors");
  39.             sockClient = socket(AF_INET,SOCK_STREAM,0);
  40.             connect(sockClient,(SOCKADDR*)&addrSrv,sizeof(SOCKADDR));
  41.         }
  42.         
  43.         Sleep(500);
  44.     }
  45.     closesocket(sockClient);
  46.     WSACleanup();
  47.     //Sleep(10000);
  48.     return;
  49.     
  50. }

vc++的程序在VS2008运行,还需要增加一个lib  #pragma comment(lib, "ws2_32.lib") 我在在编译器加 或者直接加到代码中,

程序强调,一次连接,持续发送数据,所有对一些细节如多个客户端连接的处理,没有涉及,我还有些疑问就是,发送字节不定长的处理。

  1. #include <Winsock2.h>
  2. #include <stdio.h>
  3. void main()
  4. {
  5.     WORD wVersionRequested;
  6.     WSADATA wsaData;
  7.     int err;
  8.     wVersionRequested = MAKEWORD( 2, 2 );
  9.     err = WSAStartup( wVersionRequested,&wsaData);
  10.     if( err != 0){
  11.         return;
  12.     }
  13.     if( LOBYTE( wsaData.wVersion)!= 2||
  14.         HIBYTE(wsaData.wVersion)!= 2)
  15.     {
  16.         WSACleanup();
  17.         return;
  18.     }
  19.     SOCKET sockSrv = socket(AF_INET,SOCK_STREAM,0);
  20.     SOCKADDR_IN addrSrv;
  21.     addrSrv.sin_addr.S_un.S_addr = htonl(INADDR_ANY);
  22.     addrSrv.sin_family = AF_INET;
  23.     addrSrv.sin_port= htons(6000);
  24.     bind(sockSrv,(SOCKADDR*)&addrSrv,sizeof(SOCKADDR));
  25.     err = listen(sockSrv,5);
  26.     if(err!=0)
  27.     {
  28.         //getErrors
  29.         err = WSAGetLastError();
  30.     }
  31.     SOCKADDR_IN addrClient;
  32.     int len = sizeof(SOCKADDR);
  33.     SOCKET sockConn =  accept(sockSrv,(SOCKADDR*)&addrClient,&len);
  34.     
  35.     while(1)
  36.     {
  37.         
  38.         //char sendBuf[100];
  39.         //sprintf_s(sendBuf,"Welcome %s to http://www.sunxin.org",
  40.         //  inet_ntoa(addrClient.sin_addr));
  41.         //send(sockConn,sendBuf,strlen(sendBuf)+1,0);
  42.         char recvBuf[4];
  43.         int sign = recv(sockConn,recvBuf,4,0);
  44.         printf("%s/n",recvBuf);
  45.         
  46.         
  47.     }
  48.     closesocket(sockConn);
  49.     return;
  50. }

下面是java实现的,源程序

  1. package coldwind.socket.Server;
  2. import java.net.*;
  3. import java.io.*;
  4. import eccl.socket.tools.*;
  5. public class TcpServer{
  6.     
  7.     public static void main(String[] args) throws Exception{
  8.         
  9.         ServerSocket ss = new ServerSocket(6000);
  10.         Socket s = new Socket();
  11.         
  12.         System.out.println ("start");
  13.         s = ss.accept();
  14.         System.out.println("A client has heen connected.");
  15.         DataInputStream r = new DataInputStream(s.getInputStream()); 
  16.         int count=0;
  17.         while(true){
  18.        
  19.             try {
  20.                 
  21.                 //Thread.sleep(10);
  22.                 byte c = 0;
  23.                 byte[] sendType = new byte[128];
  24. //              if(r.read()<=0)
  25. //                  continue;
  26.                 Thread.sleep(100);      
  27.                 for(int i=0;i<4;i++){
  28.                     c = r.readByte();
  29.                     sendType[i]=c;
  30.                 }
  31.                 System.out.println ("count:"+count);
  32.                 count++;
  33.                 System.out.println ("sendType: "+ByteOperator.getStr(sendType,0,4));
  34.                 
  35.             }
  36.             catch(EOFException eof)
  37.             {
  38.                 continue;
  39.             }
  40.             catch (Exception ex) {
  41.                 
  42.                 s.close();
  43.                 System.out.println (ex.toString());
  44.                 continue;
  45.                 
  46.             }
  47.             
  48.                      
  49.         }
  50.         
  51.     }
  52. }

 

 

 

  1. package coldwind.socket.Client;
  2. import java.net.*;
  3. import java.io.*;
  4. import java.sql.Connection;
  5. import java.sql.DriverManager;
  6. import java.sql.Statement;
  7. import eccl.socket.tools.ByteOperator;
  8. /**
  9.  * 发送实时数据包类
  10.  */
  11. public class TcpClient{
  12.     
  13.     public TcpClient(){
  14.         
  15.     }
  16.     private static String ip = "127.0.0.1";
  17.     private static int port = 6000;
  18.     public static Socket socket = null;
  19.     public static BufferedOutputStream bufos = null;
  20.     
  21.     public static boolean isException = false;//是否有异常
  22.     public static String errors = "";
  23. /**
  24.  *  获得与TcpServer的连接
  25.  */
  26.     public static void socketClose(){
  27.         try {
  28.             if(socket!=null){
  29.                 if(!socket.isClosed())
  30.                     socket.close();
  31.             }
  32.         } catch (IOException e) {
  33.             // TODO 自动生成 catch 块
  34.             e.printStackTrace();
  35.         }
  36.     }
  37.     
  38.     //进行连接
  39.     
  40.     public static void getTcpSocket(){
  41.         try {
  42.             SocketAddress socketAddr1 = new InetSocketAddress(ip,port);
  43.             socket = new Socket();
  44.             socket.connect(socketAddr1);
  45.                     
  46.         }
  47.         catch (Exception ex) {
  48.             System.out.println ("Do not Connect the TcpServer!/n"+ex);
  49.         }
  50.     }
  51.     
  52.     public static  void  sendThread(byte[] sendByte){
  53.         int unitNo = 0;
  54.         try{
  55.             
  56.             for(int k=0;k<5;k++)
  57.             {
  58.                 bufos = new BufferedOutputStream(socket.getOutputStream()); 
  59.                 Thread.sleep(2000);
  60.                 bufos.write(sendByte);  
  61.                 
  62.                 System.out.println ("k:"+k);
  63.                 bufos.flush();  
  64.                 
  65.                 //bufos.close();            
  66.             }
  67.             //开始时间戳,4个字节       
  68.             if(isException){
  69.                 isException = false;
  70.             }
  71.         
  72.         }catch(Exception e){
  73.             
  74.             
  75.             System.out.println(e);
  76.             if(!isException){
  77.                 isException = true;
  78.             }
  79.             
  80.             
  81.             System.out.print("RealSend The program can't send the date!/n");
  82.             //设定保存的目录
  83.             
  84.         }
  85.         
  86.         System.out.print("/n");     
  87.         
  88.     }
  89.     
  90.     public static void main(String [] arsg){
  91.         TcpClient tcpClient = new TcpClient();
  92.         getTcpSocket();
  93.         byte[] pp = new byte[4];
  94.         ByteOperator.putStr(pp,0,4,"abcd");
  95.             
  96.         sendThread(pp); 
  97.         socketClose();  
  98.     }
  99. }

 

 

 

    1. package coldwind..socket.tools;
    2. public class ByteOperator{
    3.     
    4.     public ByteOperator(){
    5.         
    6.     }
    7.      
    8.      
    9.     /**   
    10.     *   长整形转化为byte类型  
    11.     */ 
    12.     public static void putLong(byte[] buf,int offset,long value) { 
    13.         buf[offset + 0] = (byte) ((value >> 56) & 0xff); 
    14.         buf[offset + 1] = (byte) ((value >> 48) & 0xff); 
    15.         buf[offset + 2] = (byte) ((value >> 40) & 0xff); 
    16.         buf[offset + 3] = (byte) ((value >> 32) & 0xff); 
    17.         buf[offset + 4] = (byte) ((value >> 24) & 0xff); 
    18.         buf[offset + 5] = (byte) ((value >> 16) & 0xff); 
    19.         buf[offset + 6] = (byte) ((value >> 8) & 0xff); 
    20.         buf[offset + 7] = (byte) ((value >> 0) & 0xff); 
    21.     } 
    22.     
    23.     /**
    24.      *  长整形转化为byte类型
    25.      */
    26.      
    27.     public static void putReverseBytesLong(byte[] buf, int offset, long value) { 
    28.         buf[offset + 7] = (byte) (value >> 56); 
    29.         buf[offset + 6] = (byte) (value >> 48); 
    30.         buf[offset + 5] = (byte) (value >> 40); 
    31.         buf[offset + 4] = (byte) (value >> 32); 
    32.         buf[offset + 3] = (byte) (value >> 24); 
    33.         buf[offset + 2] = (byte) (value >> 16); 
    34.         buf[offset + 1] = (byte) (value >> 8); 
    35.         buf[offset + 0] = (byte) (value >> 0); 
    36.     }     
    37.      
    38.     /**
    39.      * byte 型转化为 Long 类型
    40.      */
    41.     public static long getLong(byte[] bytes, int index) { 
    42.         return ((((long) bytes[index + 0] & 0xff) << 56
    43.                 | (((long) bytes[index + 1] & 0xff) << 48
    44.                 | (((long) bytes[index + 2] & 0xff) << 40
    45.                 | (((long) bytes[index + 3] & 0xff) << 32
    46.                 | (((long) bytes[index + 4] & 0xff) << 24
    47.                 | (((long) bytes[index + 5] & 0xff) << 16
    48.                 | (((long) bytes[index + 6] & 0xff) << 8) | (((long) bytes[index + 7] & 0xff) << 0)); 
    49.     } 
    50.     /**
    51.      * byte 型转换为 Long 类型 高低位
    52.      */
    53.     public static long getReverseBytesLong(byte[] bytes, int index) { 
    54.         return ((((long) bytes[index + 7] & 0xff) << 56
    55.                 | (((long) bytes[index + 6] & 0xff) << 48
    56.                 | (((long) bytes[index + 5] & 0xff) << 40
    57.                 | (((long) bytes[index + 4] & 0xff) << 32
    58.                 | (((long) bytes[index + 3] & 0xff) << 24
    59.                 | (((long) bytes[index + 2] & 0xff) << 16
    60.                 | (((long) bytes[index + 1] & 0xff) << 8) | (((long) bytes[index + 0] & 0xff) << 0)); 
    61.     }
    62.    /**   
    63.     *   整形转化为byte类型  
    64.     */   
    65.     public static void putInt(byte[] buf,int offset,int value)   {   
    66.         buf[offset+0] = (byte)((value  >> 24) & 0xff);   
    67.         buf[offset+1] = (byte)((value  >> 16) & 0xff);   
    68.         buf[offset+2] = (byte)((value  >> 8)  & 0xff);   
    69.         buf[offset+3] = (byte)((value  >> 0)  & 0xff);   
    70.     }
    71.     
    72.     
    73.     /**
    74.      *  整型转化为byte类型 高低位
    75.      */
    76.     
    77.     public static void putReverseBytesInt(byte[] buf,int offset,int value) { 
    78.         buf[offset + 3] = (byte) (value >> 24); 
    79.         buf[offset + 2] = (byte) (value >> 16); 
    80.         buf[offset + 1] = (byte) (value >> 8); 
    81.         buf[offset + 0] = (byte) (value >> 0); 
    82.     }   
    83.     
    84.     
    85.     /**   
    86.     *   整形转化为byte类型  
    87.     */   
    88.     public static void putInt(byte[] buf,int offset,long value)   {   
    89.         buf[offset+0] = (byte)((value  >> 24) & 0xff);   
    90.         buf[offset+1] = (byte)((value  >> 16) & 0xff);   
    91.         buf[offset+2] = (byte)((value  >> 8)  & 0xff);   
    92.         buf[offset+3] = (byte)((value  >> 0)  & 0xff);   
    93.     }
    94.     
    95.     
    96.     /**
    97.      *  整型转化为byte类型 高低位
    98.      */
    99.     
    100.     public static void putReverseBytesInt(byte[] buf,int offset,long value) { 
    101.         buf[offset + 3] = (byte) (value >> 24); 
    102.         buf[offset + 2] = (byte) (value >> 16); 
    103.         buf[offset + 1] = (byte) (value >> 8); 
    104.         buf[offset + 0] = (byte) (value >> 0); 
    105.     }       
    106.     
    107.     
    108.     /**
    109.      *  byte类型转换为int型
    110.      */
    111.     
    112.     public static int getInt(byte[] bytes, int index) { 
    113.         return (int) ((((bytes[index + 0] & 0xff) << 24) | ((bytes[index + 1] & 0xff) << 16) | ((bytes[index + 2] & 0xff) << 8) | ((bytes[index + 3] & 0xff) << 0))); 
    114.     }   
    115.     
    116.     /**
    117.      *  byte类型转换为int 型 高低位
    118.      */
    119.      
    120.     public static int getReverseBytesInt(byte[] bytes, int index) { 
    121.         return (int) ((((bytes[index + 3] & 0xff) << 24
    122.                 | ((bytes[index + 2] & 0xff) << 16
    123.                 | ((bytes[index + 1] & 0xff) << 8) | ((bytes[index + 0] & 0xff) << 0))); 
    124.     }
    125.     
    126.      
    127.     /**
    128.      *  浮点型转化为byte类型
    129.      */
    130.     
    131.     public static void putFloat(byte[] buf,int offset,float value){
    132.         
    133.         try {
    134.             putInt(buf,offset,Float.floatToIntBits(value));
    135.         }
    136.         catch (Exception ex) {
    137.             System.out.print("convert the float to Byte is error!/n"+ex);
    138.         }
    139.         
    140.     }
    141.     
    142.     /**
    143.      *  浮点型转化为 byte类型 高低位
    144.      */
    145.     
    146.     public static void putReverseBytesFloat(byte[] buf,int offset,float value) { 
    147.     
    148.         try {
    149.             putReverseBytesInt(buf,offset,Float.floatToIntBits(value));
    150.         }
    151.         catch (Exception ex) {
    152.             System.out.print("convert the ReverseBytesFloat to Byte is error!/n");
    153.         }
    154.     }   
    155.     
    156.     
    157.     
    158.     /**
    159.      *  byte类型转换为浮点型
    160.      */
    161.     
    162.      public static float getReverseBytesFloat(byte[] bytes,int index){
    163.         
    164.         int num = ((bytes[index+3]<<24)0xFF000000)|((bytes[index+2]<<16)0xFF0000)|((bytes[index+1]<<8)0xFF00)|(bytes[index]0xFF);
    165.         float f = Float.intBitsToFloat(num);
    166.         return f;
    167.      }
    168.      
    169.     /**
    170.      *  byte类型转换为 浮点型 高低位
    171.      */     
    172.      
    173.      public static float getFloat (byte[] bytes, int index) { 
    174.         int num = ((bytes[index]<<24)0xFF000000)|((bytes[index+1]<<16)0xFF0000)|((bytes[index+2]<<8)0xFF00)|(bytes[index+3]0xFF);
    175.         float f = Float.intBitsToFloat(num);
    176.         return f;
    177.      }
    178.          
    179.    /**   
    180.     *   短整形转化为byte类型  
    181.     */   
    182.     public static void putShort(byte[] buf,int offset,short value)   {   
    183.         buf[offset+0] = (byte)((value  >> 8) & 0xff);   
    184.         buf[offset+1] = (byte)((value  >> 0) & 0xff);
    185.     }   
    186.     
    187.     /**
    188.      *  short 转化为 byte 类型 高低对调
    189.      */
    190.     
    191.     
    192.     public static void putReverseBytesShort(byte[] buf,int offset,short value) { 
    193.         buf[offset] = (byte) (value >> 0); 
    194.         buf[offset + 1] = (byte) (value >> 8); 
    195.     } 
    196.     
    197.     /**
    198.      *  byte 类型转换为 short型
    199.      */
    200.      
    201.     public static short getShort(byte[] bytes, int index) { 
    202.         return (short) (((bytes[index] << 8) | bytes[index + 1] & 0xff)); 
    203.     }   
    204.     
    205.     
    206.     /**
    207.      *  byte 类型转换为 short型 高低位
    208.      */
    209.     
    210.     public static short getReverseBytesShort(byte[] bytes, int index) { 
    211.         return (short) (((bytes[index + 1] << 8) | bytes[index] & 0xff)); 
    212.     }
    213.     
    214.     /**
    215.      * byte型转换为char类型
    216.      */
    217.      
    218.     public static char getChar(byte[] bytes,int index){
    219.         
    220.         return (char)(((bytes[index+1]<<8) | bytes[index] & 0xff));
    221.         
    222.     }   
    223.     
    224.     
    225.     
    226.     
    227.     /**   
    228.     *   字符串转化为byte类型  
    229.     */ 
    230.     public static void putStr(byte[] buf,int offset,int length,String value) {
    231.         try{
    232.             byte[] tmpByte = value.getBytes();
    233.             for(int i=length-1;i>=0;i--){
    234. //              buf[offset+i] = tmpByte[i]; 
    235.                 buf[offset+i] = tmpByte[i]; 
    236.             }
    237.         }catch(Exception e)
    238.         {
    239.             System.out.print("convert the String to Byte is error!/n"+e);
    240.         }
    241.     }   
    242.     
    243.     
    244.     /**
    245.      * byte型转换为字符串型
    246.      */
    247.      
    248.      public static String getStr(byte[] bytes,int index,int length){
    249.         
    250.         byte[] str = new byte[length];
    251.         for(int i=0;i<length;i++){
    252.             str[i] = bytes[index+i];    
    253.         }
    254.         
    255.         return new String(str);
    256.         
    257.      }  
    258.     
    259. }
        
  1. 以上为vc和java写的tcp的服务器端和客户端,是那种一次连接多次发送的测试例子。本人水平有限,辛苦了好久才写成功,为写应用程序做测试。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值