精华内容
下载资源
问答
  • MySQL抓包数据协议分析(客户端到服务端的通讯协议) 1典型的MySql会话过程 描述 一次正常的过程如下: 三次握手建立tcp连接 建立MySql连接 服务端往客户端发送握手初始化包(Handshake Initialization Packet) ...

    MySQL抓包数据协议分析(客户端到服务端的通讯协议)

    1典型的MySql会话过程

    描述

    一次正常的过程如下:

    1. 三次握手建立tcp连接
    2. 建立MySql连接
    1. 服务端往客户端发送握手初始化包(Handshake Initialization Packet)
    2. 客户端往服务端发送验证包(Client Authentication Packet)
    3. 服务端往客户端发送成功包
    1. 客户端与服务端之间交互
    1. 客户端往服务端发送命令包(Command Packet)
    2. 服务端往客户端发送回应包(OK Packet, or Error Packet, or Result Set Packet)

    4) 断开MySql连接

    1. 客户端往服务端发送退出命令包

    5) 四次握手断开tcp连接

    1.2 举例(使用tcpdump抓包)

    客户端在命令行模式下使用命令:mysql–u root –pdbaudit–h 192.168.86.206 连上数据库抓取的数据包如下:

    1.2.1 登陆

    1)三次握手建立连接

    19:00:22.534342 IP 192.168.86.101.59614 >localhost.localdomain.mysql: S 911022238:911022238(0) win 8192 <mss 1460,nop,wscale 2,nop,nop,sackOK>

            0x0000:  4500 0034 043f 4000 4006 0801 c0a8 5665  E..4.?@.@.....Ve

            0x0010:  c0a8 56ce e8de 0cea 364d 189e 0000 0000  ..V.....6M......

            0x0020:  8002 2000 dbdd 0000 0204 05b4 0103 0302  ................

            0x0030:  0101 0402                                ....

    19:00:22.534390 IP localhost.localdomain.mysql> 192.168.86.101.59614: S 3302432077:3302432077(0) ack 911022239 win 5840 <mss 1460,nop,nop,sackOK,nop,wscale 7>

            0x0000:  4500 0034 0000 4000 4006 0c40 c0a8 56ce  E..4..@.@..@..V.

            0x0010:  c0a8 5665 0cea e8de c4d7 1d4d 364d 189f  ..Ve.......M6M..

            0x0020:  8012 16d0 02d3 0000 0204 05b4 0101 0402  ................

            0x0030:  0103 0307                                ....

    19:00:22.534916 IP 192.168.86.101.59614 >localhost.localdomain.mysql: .ack 1 win 4380

            0x0000:  4500 0028 0440 4000 4006 080c c0a8 5665  E..(.@@.@.....Ve

            0x0010:  c0a8 56ce e8de 0cea 364d 189f c4d7 1d4e  ..V.....6M.....N

            0x0020:  5010 111c 4959 0000 0000 0000 0000       P...IY........

    2)服务端向客户諯发送握手初始化包(Handshake Initialization Packet)

    19:00:22.535632 IP localhost.localdomain.mysql> 192.168.86.101.59614: P 1:79(78) ack 1 win 46

            0x0000:  4508 0076 0d33 4000 4006 fec2 c0a8 56ce  E..v.3@.@.....V.

            0x0010:  c0a8 5665 0cea e8de c4d7 1d4e 364d 189f  ..Ve.......N6M..

            0x0020:  5018 002e 2eed 0000 4a00 0000 0a35 2e35  P.......J....5.5

            0x0030:  2e32 3100 8200 0000 2f75 2246 7b58 2652  .21...../u"F{X&R

            0x0040:  00ff f708 0200 0f80 1500 0000 0000 0000  ................

            0x0050:  0000 004b 6128 4049 2d46 565d 5366 2900  ...Ka(@I-FV]Sf).

            0x0060:  6d79 7371 6c5f 6e61 7469 7665 5f70 6173  mysql_native_pas

            0x0070:  7377 6f72 6400                           sword.

    3)客户端向服务端发送包含用户名密码的验证包(Client Authentication Packet)

    19:00:22.536678 IP 192.168.86.101.59614 >localhost.localdomain.mysql: P 1:63(62) ack 79 win 4360

            0x0000:  4500 0066 0441 4000 4006 07cd c0a8 5665  E..f.A@.@.....Ve

            0x0010:  c0a8 56ce e8de 0cea 364d 189f c4d7 1d9c  ..V.....6M......

            0x0020:  5018 1108 b2d0 0000 3a00 0001 85a6 0300  P.......:.......

            0x0030:  0000 0001 0800 0000 0000 0000 0000 0000  ................

            0x0040:  0000 0000 0000 0000 0000 0000 726f 6f74  ............root

            0x0050:  0014 ce03 1683 429e cae8 cb93 5435 71f2  ......B.....T5q.

            0x0060:  7439 d842 1922                           t9.B."

    4)服务端向客户端发送一个空包(普通的tcp包,跟mysql无关)

    19:00:22.536748 IP localhost.localdomain.mysql> 192.168.86.101.59614: .ack 63 win 46

            0x0000:  4508 0028 0d34 4000 4006 ff0f c0a8 56ce  E..(.4@.@.....V.

            0x0010:  c0a8 5665 0cea e8de c4d7 1d9c 364d 18dd  ..Ve........6M..

            0x0020:  5010 002e 59bb 0000                      P...Y...

    5)服务端向客户端发送一个成功包(OK Packet)

    19:00:22.536827 IP localhost.localdomain.mysql> 192.168.86.101.59614: P 79:90(11) ack 63 win 46

            0x0000:  4508 0033 0d35 4000 4006 ff03 c0a8 56ce  E..3.5@.@.....V.

            0x0010:  c0a8 5665 0cea e8de c4d7 1d9c 364d 18dd  ..Ve........6M..

            0x0020:  5018 002e 2eaa 0000 0700 0002 0000 0002  P...............

            0x0030:  0000 00                                  ...

    6)客户端向服务端发送一个包(跟mysql似乎无关,包头不符合协议标准)

    19:00:22.734205 IP 192.168.86.101.59614 >localhost.localdomain.mysql: .ack 90 win 4357

            0x0000:  4500 0028 0444 4000 4006 0808 c0a8 5665  E..(.D@.@.....Ve

            0x0010:  c0a8 56ce e8de 0cea 364d 18dd c4d7 1da7  ..V.....6M......

            0x0020:  5010 1105 48d9 0000 0000 0000 0000       P...H.........

     

    1.2.2 客户端与服务端之间交互

    客户端输入:usemysql

    服务端返回:Database changed

    1)客户端向服务端发送一个命令包(类型为COM_QUERY)

    19:07:56.352167 IP 192.168.86.101.59614 >localhost.localdomain.mysql: P 911022301:911022323(22) ack 3302432167 win 4357

            0x0000:  4500 003e 0450 4000 4006 07e6 c0a8 5665  E..>.P@.@.....Ve

            0x0010:  c0a8 56ce e8de 0cea 364d 18dd c4d7 1da7  ..V.....6M......

            0x0020:  5018 1105 fe85 0000 1200 0000 0353 454c  P............SEL

            0x0030:  4543 5420 4441 5441 4241 5345 2829       ECT.DATABASE()

    2)服务端向客户端发送一个结果包(ResultSet)

    一个ResultSet包含了多个包,每个包都有自己的包头包体,

    下面这个返回数据就包含了五个包(1个ResultSet Head Packet + 1个Field Packet + 1个EOF Packet + 1个Row Data Packet + 1个EOF Packet)

    19:07:56.352413 IP localhost.localdomain.mysql> 192.168.86.101.59614: P 1:65(64) ack 22 win 46

            0x0000:  4508 0068 0d36 4000 4006 fecd c0a8 56ce  E..h.6@.@.....V.

            0x0010:  c0a8 5665 0cea e8de c4d7 1da7 364d 18f3  ..Ve........6M..

            0x0020:  5018 002e 2edf 0000 0100 0001 0120 0000  P...............

            0x0030:  0203 6465 6600 0000 0a44 4154 4142 4153  ..def....DATABAS

            0x0040:  4528 2900 0c08 0022 0000 00fd 0000 1f00  E()...."........

            0x0050:  0005 0000 03fe 0000 0200 0100 0004 fb05  ................

            0x0060:  0000 05fe 0000 0200                      ........

    3)客户端向服务端发送一个命令包(类型为COM_INIT_DB)

    19:07:56.353134 IP 192.168.86.101.59614 >localhost.localdomain.mysql: P 22:32(10) ack 65 win 4341

            0x0000:  4500 0032 0451 4000 4006 07f1 c0a8 5665  E..2.Q@.@.....Ve

            0x0010:  c0a8 56ce e8de 0cea 364d 18f3 c4d7 1de7  ..V.....6M......

            0x0020:  5018 10f5 5534 0000 0600 0000 026d 7973  P...U4.......mys

            0x0030:  716c                                     ql

    4)服务端向客户端发送一个成功包(OK Packet)

    19:07:56.367217 IP localhost.localdomain.mysql> 192.168.86.101.59614: P 65:76(11) ack 32 win 46

            0x0000:  4508 0033 0d37 4000 4006 ff01 c0a8 56ce  E..3.7@.@.....V.

            0x0010:  c0a8 5665 0cea e8de c4d7 1de7 364d 18fd  ..Ve........6M..

            0x0020:  5018 002e 2eaa 0000 0700 0001 0000 0002  P...............

            0x0030:  0000 00                                  ...

    5)客户端向服务端发送一个包(跟mysql没什么关系,包头为0000 0000)

    19:07:56.561717 IP 192.168.86.101.59614 >localhost.localdomain.mysql: .ack 76 win 4339

            0x0000:  4500 0028 0455 4000 4006 07f7 c0a8 5665  E..(.U@.@.....Ve

            0x0010:  c0a8 56ce e8de 0cea 364d 18fd c4d7 1df2  ..V.....6M......

            0x0020:  5010 10f3 4880 0000 0000 0000 0000       P...H.........

     

    客户端输入:show tables

    服务端返回:查询结果,当前数据库中所有的表

    1)客户端向服务端发送一个命令包(类型为COM_QUERY)

    19:22:17.971933 IP 192.168.86.101.59614 >localhost.localdomain.mysql: P 911022333:911022349(16) ack 3302432242 win 4339

            0x0000:  4500 0038 0466 4000 4006 07d6 c0a8 5665  E..8.f@.@.....Ve

            0x0010:  c0a8 56ce e8de 0cea 364d 18fd c4d7 1df2  ..V.....6M......

            0x0020:  5018 10f3 1d24 0000 0c00 0000 0373 686f  P....$.......sho

            0x0030:  7720 7461 626c 6573                      w.tables

    2)服务端向客户端发送一个普通的tcp包

    19:22:18.011368 IP localhost.localdomain.mysql> 192.168.86.101.59614: .ack 16 win 46

            0x0000:  4508 0028 0d38 4000 4006 ff0b c0a8 56ce  E..(.8@.@.....V.

            0x0010:  c0a8 5665 0cea e8de c4d7 1df2 364d 190d  ..Ve........6M..

            0x0020:  5010 002e 5935 0000                      P...Y5..

    3)服务端向客户端发送一个响应结果包(Result Packets)

    19:22:18.031320 IP localhost.localdomain.mysql> 192.168.86.101.59614: P 1:521(520) ack 16 win 46

            0x0000:  4508 0230 0d39 4000 4006 fd02 c0a8 56ce  E..0.9@.@.....V.

            0x0010:  c0a8 5665 0cea e8de c4d7 1df2 364d 190d  ..Ve........6M..

            0x0020:  5018 002e 30a7 0000 0100 0001 0157 0000  P...0........W..

            0x0030:  0203 6465 6612 696e 666f 726d 6174 696f  ..def.informatio

            0x0040:  6e5f 7363 6865 6d61 0b54 4142 4c45 5f4e  n_schema.TABLE_N

            0x0050:  414d 4553 0b54 4142 4c45 5f4e 414d 4553  AMES.TABLE_NAMES

            0x0060:  0f54 6162 6c65 735f 696e 5f6d 7973 716c  .Tables_in_mysql

            0x0070:  0a54 4142 4c45 5f4e 414d 450c 0800 4000  .TABLE_NAME...@.

            0x0080:  0000 fd01 0000 0000 0500 0003 fe00 0022  ..............."

            0x0090:  000d 0000 040c 636f 6c75 6d6e 735f 7072  ......columns_pr

            0x00a0:  6976 0300 0005 0264 620a 0000 0609 6462  iv.....db.....db

            0x00b0:  5f6f 705f 6c6f 6706 0000 0705 6576 656e  _op_log.....even

            0x00c0:  7405 0000 0804 6675 6e63 0c00 0009 0b67  t.....func.....g

            0x00d0:  656e 6572 616c 5f6c 6f67 0e00 000a 0d68  eneral_log.....h

            0x00e0:  656c 705f 6361 7465 676f 7279 0d00 000b  elp_category....

            0x00f0:  0c68 656c 705f 6b65 7977 6f72 640e 0000  .help_keyword...

            0x0100:  0c0d 6865 6c70 5f72 656c 6174 696f 6e0b  ..help_relation.

            0x0110:  0000 0d0a 6865 6c70 5f74 6f70 6963 0500  ....help_topic..

            0x0120:  000e 0468 6f73 7411 0000 0f10 6e64 625f  ...host.....ndb_

            0x0130:  6269 6e6c 6f67 5f69 6e64 6578 0700 0010  binlog_index....

            0x0140:  0670 6c75 6769 6e05 0000 1104 7072 6f63  .plugin.....proc

            0x0150:  0b00 0012 0a70 726f 6373 5f70 7269 760d  .....procs_priv.

            0x0160:  0000 130c 7072 6f78 6965 735f 7072 6976  ....proxies_priv

            0x0170:  0800 0014 0773 6572 7665 7273 0900 0015  .....servers....

            0x0180:  0873 6c6f 775f 6c6f 670c 0000 160b 7461  .slow_log.....ta

            0x0190:  626c 6573 5f70 7269 7605 0000 1704 7465  bles_priv.....te

            0x01a0:  7374 0600 0018 0574 6573 7431 0a00 0019  st.....test1....

            0x01b0:  0974 696d 655f 7a6f 6e65 1600 001a 1574  .time_zone.....t

            0x01c0:  696d 655f 7a6f 6e65 5f6c 6561 705f 7365  ime_zone_leap_se

            0x01d0:  636f 6e64 0f00 001b 0e74 696d 655f 7a6f  cond.....time_zo

            0x01e0:  6e65 5f6e 616d 6515 0000 1c14 7469 6d65  ne_name.....time

            0x01f0:  5f7a 6f6e 655f 7472 616e 7369 7469 6f6e  _zone_transition

            0x0200:  1a00 001d 1974 696d 655f 7a6f 6e65 5f74  .....time_zone_t

            0x0210:  7261 6e73 6974 696f 6e5f 7479 7065 0500  ransition_type..

            0x0220:  001e 0475 7365 7205 0000 1ffe 0000 2200  ...user.......".

    4) 客户端向服务端发送一个普通的tcp包

    19:22:18.232503 IP 192.168.86.101.59614 >localhost.localdomain.mysql: .ack 521 win 4209

            0x0000:  4500 0028 046b 4000 4006 07e1 c0a8 5665  E..(.k@.@.....Ve

            0x0010:  c0a8 56ce e8de 0cea 364d 190d c4d7 1ffa  ..V.....6M......

            0x0020:  5010 1071 46ea 0000 0000 0000 0000       P..qF.........

    1.2.3 退出

    客户端在命令行模式下输入命令:quit 退出数据库

    1)客户端向服务端发送一个退出的命令包

    15:50:46.533701 IP 192.168.86.101.58767 >localhost.localdomain.mysql: P 829834420:829834425(5) ack 3239997079 win 4357

            0x0000:  4500 002d 039d 4000 4006 08aa c0a8 5665  E..-..@.@.....Ve

            0x0010:  c0a8 56ce e58f 0cea 3176 44b4 c11e 6e97  ..V.....1vD...n.

            0x0020:  5018 1105 d5e3 0000 0100 0000 0100       P.............

    2)三次握手断开连接(断开连接不是四次握手吗?但实际情况下测试如果是正常的退出只有三次握手的过程)

    15:50:46.533733 IP 192.168.86.101.58767 >localhost.localdomain.mysql: F 5:5(0) ack 1 win 4357

            0x0000:  4500 0028 039e 4000 4006 08ae c0a8 5665  E..(..@.@.....Ve

            0x0010:  c0a8 56ce e58f 0cea 3176 44b9 c11e 6e97  ..V.....1vD...n.

            0x0020:  5011 1105 d7ea 0000 0000 0000 0000       P.............

    15:50:46.533854 IP localhost.localdomain.mysql> 192.168.86.101.58767: F 1:1(0) ack 6 win 46

            0x0000:  4508 0028 648b 4000 4006 a7b8 c0a8 56ce  E..(d.@.@.....V.

            0x0010:  c0a8 5665 0cea e58f c11e 6e97 3176 44ba  ..Ve......n.1vD.

            0x0020:  5011 002e e8c0 0000                      P.......

    15:50:46.534434 IP 192.168.86.101.58767 >localhost.localdomain.mysql: .ack 2 win 4357

            0x0000:  4500 0028 039f 4000 4006 08ad c0a8 5665  E..(..@.@.....Ve

            0x0010:  c0a8 56ce e58f 0cea 3176 44ba c11e 6e98  ..V.....1vD...n.

            0x0020:  5010 1105 d7e9 0000 0000 0000 0000       P.............

    2.MySql数据包结构的描述

    2.1 包头(Packet Header)

    每个数据包都有一个包头,具体格式如下:

    Bytes                 Name

     -----                 ----

     3                     Packet Length

     1                     Packet Number

     

     Packet Length: The length, in bytes, of the packet

    that follows the Packet Header. There

    may be some special values in the most

    significant byte. The maximum packet

    length is (2**24 -1),about 16MB.

     

     Packet Number: A serial number which can be used to

    ensure that all packets are present

    and in order. The first packet of a

    client query will have Packet Number = 0

                    Thus, when a new SQL statement starts,

    the packet number is re-initialised.

     

    2.2 数据包

    2.2.1 握手初始化包(Handshake Initialization Packet

    2.2.1.1 格式描述

    Bytes                        Name

     -----                        ----

     1                            protocol_version

    n (Null-Terminated String)   server_version

     4                            thread_id

     8                            scramble_buff

     1                            (filler) always 0x00

     2                            server_capabilities

     1                            server_language

     2                            server_status

     2                            server capabilities (two upper bytes)

     1                            length of the scramble

    10                            (filler)  always 0

    n                            rest of the plugin provided data (at least 12 bytes)

     1                            \0 byte, terminating the second part of a scramble

     

    protocol_version:    The server takes this from PROTOCOL_VERSION

    in /include/mysql_version.h. Example value = 10.

     

    server_version:      The server takes this from MYSQL_SERVER_VERSION

    in /include/mysql_version.h. Example value = "4.1.1-alpha".

     

    thread_number:       ID of the server thread for this connection.

     

    scramble_buff:       The password mechanism uses this. The second part are the

    last 13 bytes.

                          (See "Password functions" section elsewhere in this document.)

     

    server_capabilities: CLIENT_XXX options. The possible flag values at time of

    writing (taken from  include/mysql_com.h):

      CLIENT_LONG_PASSWORD 1 /* new more secure passwords */

      CLIENT_FOUND_ROWS 2 /* Found instead of affected rows */

      CLIENT_LONG_FLAG 4 /* Get all column flags */

      CLIENT_CONNECT_WITH_DB 8 /* One can specify db on connect */

      CLIENT_NO_SCHEMA 16 /* Don't allow database.table.column */

      CLIENT_COMPRESS 32 /* Can use compression protocol */

      CLIENT_ODBC 64 /* Odbc client */

      CLIENT_LOCAL_FILES 128 /* Can use LOAD DATA LOCAL */

      CLIENT_IGNORE_SPACE 256 /* Ignore spaces before '(' */

      CLIENT_PROTOCOL_41 512 /* New 4.1 protocol */

      CLIENT_INTERACTIVE 1024 /* This is an interactive client */

      CLIENT_SSL              2048 /* Switch to SSL after handshake */

      CLIENT_IGNORE_SIGPIPE   4096    /* IGNORE sigpipes */

      CLIENT_TRANSACTIONS 8192 /* Client knows about transactions */

      CLIENT_RESERVED         16384   /* Old flag for 4.1 protocol  */

      CLIENT_SECURE_CONNECTION 32768  /* New 4.1 authentication */

      CLIENT_MULTI_STATEMENTS 65536   /* Enable/disable multi-stmt support */

      CLIENT_MULTI_RESULTS    131072  /* Enable/disable multi-results */

     

    server_language:     current server character set number

     

    server_status:       SERVER_STATUS_xxx flags: e.g. SERVER_STATUS_AUTOCOMMIT

    2.2.1.2 举例

    Example Handshake Initialization Packet

                        Hexadecimal                ASCII

                        -----------                -----

    protocol_version    0a                         .

    server_version      34 2e 31 2e 31 2d 71 6c    4.1.1-al

                        70 68 61 2d 64 65 62 75    pha-debu

    67 00                      g.

    thread_number       01 00 00 00                ....

    scramble_buff       3a 23 3d 4b 43 4a 2e 43    ........

    (filler)            00                         .

    server_capabilities 2c 82                      ..

    server_language     08                         .

    server_status       02 00                      ..

    (filler)            00 00 00 00 00 00 00 00    ........

                        00 00 00 00 00

    2.2.2 客户端验证包(Client Authentication Packet)

    2.2.2.1 格式描述

    VERSION 4.0

     Bytes                        Name

     -----                        ----

     2                            client_flags

     3                            max_packet_size

    n  (Null-Terminated String)  user

     8                            scramble_buff

     1                            (filler) always 0x00

     

     VERSION 4.1

     Bytes                        Name

     -----                        ----

     4                            client_flags

     4                            max_packet_size

     1                            charset_number

     23                           (filler) always 0x00...

    n (Null-Terminated String)   user

    n (Length Coded Binary)      scramble_buff (1 + x bytes)

    n (Null-Terminated String)   databasename (optional)

     

    client_flags:            CLIENT_xxx options. The list of possible flag

    values is in the description of the Handshake

    Initialisation Packet, for server_capabilities.

                              For some of the bits, the server passed "what

    it's capable of". The client leaves some of the

    bits on, adds others, and passes back to the server.

                              One important flag is: whether compression is desired.

                              Another interesting one is: CLIENT_CONNECT_WITH_DB,

    which shows the presence of the optional databasename.

     

    max_packet_size:         the maximum number of bytes in a packet for the client

     

    charset_number:          in the same domain as the server_language field that

    the server passes in the Handshake Initialization packet.

     

    user:                    identification

     

    scramble_buff:           the password, after encrypting using the scramble_buff

    contents passed by the server (see "Password functions"

    section elsewhere in this document)

    if length is zero, no password was given

     

    databasename:            name of schema to use initially

     

    2.2.2.2 举例

    Example Client Authentication Packet

                        Hexadecimal                ASCII

                        -----------                -----

    client_flags        85 a6 03 00                ....

    max_packet_size     00 00 00 01                ....

    charset_number      08                         .

    (filler)            00 00 00 00 00 00 00 00    ........

                        00 00 00 00 00 00 00 00    ........

                        00 00 00 00 00 00 00       .......

    user                70 67 75 6c 75 74 7a 61    pgulutza

    6e 00                      n.

     

    2.2.3 命令包

    2.2.3.1 格式描述

    Bytes                        Name

     -----                        ----

     1                            command

    narg

     

    command:      The most common value is 03 COM_QUERY, because

                   INSERT UPDATE DELETE SELECT etc. have this code.

                   The possible values at time of writing (taken

    from /include/mysql_com.h for enum_server_command) are:

     

                   #      Name                Associated client function

                   -      ----                --------------------------

     

                   0x00   COM_SLEEP           (none, this is an internal thread state)

                   0x01   COM_QUIT            mysql_close

                   0x02   COM_INIT_DB         mysql_select_db

                   0x03   COM_QUERY           mysql_real_query

                   0x04   COM_FIELD_LIST      mysql_list_fields

                   0x05   COM_CREATE_DB       mysql_create_db (deprecated)

                   0x06   COM_DROP_DB         mysql_drop_db (deprecated)

                   0x07   COM_REFRESH         mysql_refresh

                   0x08   COM_SHUTDOWN        mysql_shutdown

                   0x09   COM_STATISTICS      mysql_stat

                   0x0a   COM_PROCESS_INFO    mysql_list_processes

                   0x0b   COM_CONNECT         (none, this is an internal thread state)

                   0x0c   COM_PROCESS_KILL    mysql_kill

                   0x0d   COM_DEBUG           mysql_dump_debug_info

                   0x0e   COM_PING            mysql_ping

                   0x0f   COM_TIME            (none, this is an internal thread state)

                   0x10   COM_DELAYED_INSERT  (none, this is an internal thread state)

                   0x11   COM_CHANGE_USER     mysql_change_user

                   0x12   COM_BINLOG_DUMP     sent by the slave IO thread to request a binlog

                   0x13   COM_TABLE_DUMP      LOAD TABLE ... FROM MASTER (deprecated)

                   0x14   COM_CONNECT_OUT     (none, this is an internal thread state)

                   0x15   COM_REGISTER_SLAVE  sent by the slave to register with the master (optional)

                   0x16   COM_STMT_PREPARE    mysql_stmt_prepare

                   0x17   COM_STMT_EXECUTE    mysql_stmt_execute

                   0x18   COM_STMT_SEND_LONG_DATA mysql_stmt_send_long_data

                   0x19   COM_STMT_CLOSE      mysql_stmt_close

                   0x1a   COM_STMT_RESET      mysql_stmt_reset

                   0x1b   COM_SET_OPTION      mysql_set_server_option

                   0x1c   COM_STMT_FETCH      mysql_stmt_fetch

     

    arg:           The text of the command is just the way the user typed it, there is no processing

    by the client (except removal of the final ';').

                    This field is not a null-terminated string; however,

    the size can be calculated from the packet size,

    and the MySQL client appends '\0' when receiving.

     

    2.2.3.2 举例

    Example Command Packet

                        Hexadecimal                ASCII

                        -----------                -----

    command             02                         .

    arg                 74 65 73 74                test

     

    2.2.4 响应包

    2.2.4.1 成功包

    2.2.4.1.1 格式描述

    VERSION 4.0

     Bytes                       Name

     -----                       ----

     1   (Length Coded Binary)   field_count, always = 0

     1-9 (Length Coded Binary)   affected_rows

     1-9 (Length Coded Binary)   insert_id

     2                           server_status

    n   (until end of packet)   message

     

     VERSION 4.1

     Bytes                       Name

     -----                       ----

     1   (Length Coded Binary)   field_count, always = 0

     1-9 (Length Coded Binary)   affected_rows

     1-9 (Length Coded Binary)   insert_id

     2                           server_status

     2                           warning_count

    n   (until end of packet)   message

     

    field_count:     always = 0

     

    affected_rows:   = number of rows affected by INSERT/UPDATE/DELETE

     

    insert_id:       If the statement generated any AUTO_INCREMENT number,

    the number is returned here. Otherwise this field contains 0.

                      Note: when using for example a multiple row INSERT the

    insert_id will be from the first row inserted, not from

    last.

     

    server_status:   = The client can use this to check if the

    command was inside a transaction.

     

    warning_count:   number of warnings

     

    message:         For example, after a multi-line INSERT, message might be

                      "Records: 3 Duplicates: 0 Warnings: 0"

     

    2.2.4.1.2 举例

    Example OK Packet

                        Hexadecimal                ASCII

                        -----------                -----

    field_count         00                         .

    affected_rows       01                         .

    insert_id           00                         .

    server_status       02 00                      ..

    warning_count       00 00                      ..

     

    2.2.4.2 错误包

    2.2.4.2.1 格式描述

    VERSION 4.0

     Bytes                       Name

     -----                       ----

     1                           field_count, always = 0xff

     2                           errno (little endian)

    n                           message

     

     VERSION 4.1

     Bytes                       Name

     -----                       ----

     1                           field_count, always = 0xff

     2                           errno

     1                           (sqlstate marker), always '#'

     5                           sqlstate (5 characters)

    n                           message

     

    field_count:       Always 0xff (255 decimal).

     

    errno:             The possible values are listed in the manual, and in

    the MySQL source code file /include/mysqld_error.h.

     

    sqlstate marker:   This is always '#'. It is necessary for distinguishing

    version-4.1 messages.

     

    sqlstate:          The server translates errno values to sqlstate values

    with a function named mysql_errno_to_sqlstate(). The

    possible values are listed in the manual, and in the

                        MySQL source code file /include/sql_state.h.

     

    message:           The error message is a string which ends at the end of

    the packet, that is, its length can be determined from

    the packet header. The MySQL client (in the my_net_read()

    function) always adds '\0' to a packet, so the message

    may appear to be a Null-Terminated String.

                        Expect the message to be between 0 and 512 bytes long.

     

    2.2.4.2.2 举例

    Example of Error Packet

                        Hexadecimal                ASCII

                        -----------                -----

    field_countff                         .

    errno               1b 04                      ..

    (sqlstate marker)   23                         #

    sqlstate            34 32 53 30 32             42S02

    message             55 63 6b 6e 6f 77 6e 20    Unknown

                        74 61 62 6c 6c 65 20 27    table '

                        71 27                      q'

     

    2.2.4.3 结果集包

    一个结果集包由多个数据包组成,数据结构如下(按顺序列出):

    1. 结果集头部包(Result Set Header Packet)(1个)the number of columns
    2. 字段包(Field Packet)(n个) column descriptors
    3. 分隔包(EOF Packet)(1个) marker: end of Field Packets
    4. 行数据包(Row Data Packets)(n个) row contents
    5. 分隔包(EOF Packet)(1个) marker: end of Field Packets

    如,下面是当客户端使用select count(*) from user语句查询时tcpdump抓取的数据包:

    客户端输入:select count(*) from user

    服务端返回:查询结果

    mysql> select count(*) from user;

    +----------+

    | count(*) |

    +----------+

    |       11 |

    +----------+

    1 row in set (0.00 sec)

    1)客户端向服务端发送命令包

    18:26:36.054761 IP 192.168.86.101.61382 >localhost.localdomain.mysql: P 454811053:454811083(30) ack 3069793847 win 4209

            0x0000:  4500 0046 04bd 4000 4006 0771 c0a8 5665  E..F..@.@..q..Ve

            0x0010:  c0a8 56ce efc6 0cea 1b1b ddad b6f9 5637  ..V...........V7

            0x0020:  5018 1071 bf9f 0000 1a00 0000 0373 656c  P..q.........sel

            0x0030:  6563 7420 636f 756e 7428 2a29 2066 726f  ect.count(*).fro

            0x0040:  6d20 7573 6572                           m.user

    2)服务端向客户端发送一个普通tcp包

    18:26:36.054762 IP localhost.localdomain.mysql> 192.168.86.101.61382: .ack 30 win 46

            0x0000:  4508 0028 594f 4000 4006 b2f4 c0a8 56ce  E..(YO@.@.....V.

            0x0010:  c0a8 5665 0cea efc6 b6f9 5637 1b1b ddcb  ..Ve......V7....

            0x0020:  5010 002e 7e59 0000                      P...~Y..

    3)服务端向客户端发送一个结果集包

    18:26:36.054980 IP localhost.localdomain.mysql> 192.168.86.101.61382: P 1:65(64) ack 30 win 46

            0x0000:  4508 0068 5950 4000 4006 b2b3 c0a8 56ce  E..hYP@.@.....V.

            0x0010:  c0a8 5665 0cea efc6 b6f9 5637 1b1b ddcb  ..Ve......V7....

            0x0020:  5018 002e 2edf 0000 0100 0001 011e 0000  P...............

            0x0030:  0203 6465 6600 0000 0863 6f75 6e74 282a  ..def....count(*

            0x0040:  2900 0c3f 0015 0000 0008 8100 0000 0005  )..?............

            0x0050:  0000 03fe 0000 0200 0300 0004 0231 3105  .............11.

            0x0060:  0000 05fe 0000 0200                      ........

    4)客户端向客户端发送一个普通tcp包

    18:26:36.254624 IP 192.168.86.101.61382 >localhost.localdomain.mysql: .ack 65 win 4193

            0x0000:  4500 0028 04bf 4000 4006 078d c0a8 5665  E..(..@.@.....Ve

            0x0010:  c0a8 56ce efc6 0cea 1b1b ddcb b6f9 5677  ..V...........Vw

            0x0020:  5010 1061 6de6 0000 0000 0000 0000       P..am.........

    其中第三个包是结果集包,去除ip头和tcp头后红色部分即为真正的数据包:

    4508 0068 5950 4000 4006 b2b3 c0a8 56ce  E..hYP@.@.....V.

    c0a8 5665 0cea efc6 b6f9 5637 1b1b ddcb  ..Ve......V7....

    5018 002e 2edf 0000 0100 0001 011e 0000  P...............

    0203 6465 6600 0000 0863 6f75 6e74 282a  ..def....count(*

    2900 0c3f 0015 0000 0008 8100 0000 0005  )..?............

    0000 03fe 0000 0200 0300 0004 0231 3105  .............11.

    0000 05fe 0000 0200

    进一步对其分析如下(蓝色字体为包头):

    Result Set Header Packet

    0100 000101 .....

    Field Packet

    1e 0000  ........

    0203 6465 6600 0000 0863 6f75 6e74 282a  ..def....count(*

    2900 0c3f 0015 0000 0008 8100 0000 00     )..?...........

    EOF Packet

    05 0000 03fe 0000 0200 .............

    Row Data Packet

    0300 0004 0231 31 .....11

    EOF Packet

    05 0000 05fe 0000 0200 .........

    2.2.4.3.1结果集头部包(Result Set Header Packet

    2.2.4.3.1.1 格式描述

    Bytes                        Name

     -----                        ----

     1-9   (Length-Coded-Binary)  field_count

     1-9   (Length-Coded-Binary)  extra

     

    field_count: See the section "Types Of Result Packets"

    to see how one can distinguish the

    first byte of field_count from the first

    byte of an OK Packet, or other packet types.

     

    extra:       For example, SHOW COLUMNS uses this to send

    the number of rows in the table.

     

    2.2.4.3.1.2 举例

    Example of Result Set Header Packet

                        Hexadecimal                ASCII

                        -----------                -----

    field_count         03               

     

    2.2.4.3.2字段包(Field Packet)

    2.2.4.3.2.1 格式描述

    VERSION 4.0

     Bytes                      Name

     -----                      ----

    n (Length Coded String)    table

    n (Length Coded String)    name

     4 (Length Coded Binary)    length

     2 (Length Coded Binary)    type

     2 (Length Coded Binary)    flags

    1                          decimals

    n (Length Coded Binary)    default

     

     VERSION 4.1

     Bytes                      Name

     -----                      ----

    n (Length Coded String)    catalog

    n (Length Coded String)    db

    n (Length Coded String)    table

    n (Length Coded String)    org_table

    n (Length Coded String)    name

    n (Length Coded String)    org_name

     1                          (filler)

     2                          charsetnr

    4                          length

     1                          type

     2                          flags

    1                          decimals

     2                          (filler), always 0x00

    n (Length Coded Binary)    default

     

    2.2.4.3.2.2 举例

    Example of Field Packet

                        Hexadecimal                ASCII

                        -----------                -----

    catalog             03 73 74 64                .std

    db                  03 64 62 31                .db1

    table               02 54 37                   .T7

    org_table           02 74 37                   .t7

    name                02 53 31                   .S1

    org_name            02 73 31                   .s1

    (filler)            0c                         .

    charsetnr           08 00                      ..

    length              01 00 00 00                ....

    typefe                         .

    flags               00 00                      ..

    decimals            00                         .

    (filler)            00 00                      ..

     

     

    2.2.4.3.3分隔包(EOF Packet)

    2.2.4.3.3.1 格式描述

    VERSION 4.0

     Bytes                 Name

     -----                 ----

     1                     field_count, always = 0xfe

     

     VERSION 4.1

     Bytes                 Name

     -----                 ----

     1                     field_count, always = 0xfe

     2                     warning_count

     2                     Status Flags

     

    field_count:          The value is always 0xfe (decimal 254).

                           However ... recall (from the

    section "Elements", above) that the value 254 can begin

    a Length-Encoded-Binary value which contains an 8-byte

    integer. So, to ensure that a packet is really an EOF

                           Packet: (a) check that first byte in packet = 0xfe, (b)

    check that size of packet < 9.

     

    warning_count:        Number of warnings. Sent after all data has been sent

    to the client.

     

    server_status:        Contains flags like SERVER_MORE_RESULTS_EXISTS

     

     

    2.2.4.3.3.2 举例

    Example of EOF Packet

                        Hexadecimal                ASCII

                        -----------                -----

    field_countfe                         .

    warning_count       00 00                      ..

    server_status       00 00                      ..

     

    2.2.4.3.4 行数据包

    2.2.4.3.4.1 格式描述

    Bytes                   Name

     -----                   ----

    n (Length Coded String) (column value)

     ...

     

     (column value):       The data in the column, as a character string.

                           If a column is defined as non-character, the

    server converts the value into a character

    before sending it. Since the value is a Length

                           Coded String, a NULL can be represented with a

    single byte containing 251(see the description

    of Length Coded Strings in section "Elements" above).

     

    2.2.4.3.4.2 举例

    Example of Row Data Packet

                        Hexadecimal                ASCII

                        -----------                -----

    (first column)      01 58                      .X

    (second column)     02 35 35                   .55

    展开全文
  • TCP协议发送和接收数据

    千次阅读 2019-02-25 21:12:39
    刚学习入门了TCP协议,其简单的发送和接收数据的原理并不难,下面是一些步骤的总结和实际操作的代码。敬请斧正! 一,TCP协议发送数据:  1,创建发送端的Socket对象 2,获取输出流,写数据 3,释放资源   ...

    刚学习入门了TCP协议,其简单的发送和接收数据的原理并不难,下面是一些步骤的总结和实际操作的代码。敬请斧正!

    一,TCP协议发送数据: 

    1,创建发送端的Socket对象

    2,获取输出流,写数据

    3,释放资源

     

    package time_2_25;
    
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.net.Socket;
    
    public class ClientDemo {
    public static void main(String[] args) throws IOException{
    	
    	//创建客户端的socket对象
    	Socket s = new Socket("198.168.12.123", 6666);//服务器的ip地址和端口号
    	
    	//获取输出流
    	OutputStream os = s.getOutputStream();
    	os.write("Hello tcp!".getBytes());
    	
    	//获取输入流
    	InputStream is = s.getInputStream();
    	byte[] bys = new byte[1024];
    	int len = is.read(bys);
    	String str = new String(bys,0,len);
    	System.out.println("来自服务端:"+str);//服务器接收到消息后的反馈
    	
    	//释放资源
    	s.close(); 
    }
    }
    

    二,TCP协议接收数据

    1,创建接收端的Socket对象

    2,监听客户端的连接(Socket s = ss.accept();

    3,获取输入流,读取数据显示在控制台(这里可以给发送端一个接收到信息的反馈:

      OutputStream os = s.getOutputStream();os.write("消息已经收到".getBytes());

    4,释放资源

    package time_2_25;
    
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.net.ServerSocket;
    import java.net.Socket;
    
    public class ServerDemo {
    public static void main(String[] args) throws IOException{
    	//创建服务器ServerSocket对象
    	ServerSocket ss = new ServerSocket(6666);
    	
    	//监听客户端的连接
    	Socket s = ss.accept();//在连接传入之前一直阻塞,接收到后开始执行后面的
    	//获取输入流
    	InputStream is = s.getInputStream();
    	byte[] bys = new byte[1024];
    	int len = is.read(bys);
    	String str = new String(bys,0,len);
    	
    	//将从客户端传来的消息输出到控制台
    	System.out.println("来自客户端:"+str);
    	
    	//给出获得消息后的反馈
    	OutputStream os = s.getOutputStream();
    	os.write("消息已经收到".getBytes());
    	
    	//释放资源
    	s.close();
    }
    }
    

     

    三,作图辅助理解

    为了方便理解,这里我制作了一张PPT方便和我一样的初学者学习,制作的较为粗糙,请见谅。

    展开全文
  • Java通过Exchange协议发送和接收邮件

    热门讨论 2014-03-14 14:15:01
    本段程序实现java通过exchange协议发送和接收邮件功能。实现了发送邮件、接收未读邮件和已读邮件的功能。采用微软官方提供的EWSJavaAPI_1.2.jar包完成此项功能。
  • API-网络编程(网络概述,Socket通信机制,UDP协议发送和接收数据,TCP协议发送和接收数据)

    1:网络编程(理解)

    (1)网络编程:用Java语言实现计算机间数据的信息传递和资源共享

    (2)网络编程模型

    l网络模型一般是指
    OSI(Open System Interconnection开放系统互连)参考模型
    TCP/IP参考模型


    (3)网络编程的三要素


    A:IP地址


    a:点分十进制

    计算机只能识别二进制的数据,所以我们的IP地址应该是一个二进制的数据。
    但是呢,我们配置的IP地址确不是二进制的,为什么呢?
    IP:192.168.1.100
    换算:11000000 10101000 00000001 01100100
    假如真是:11000000 10101000 00000001 01100100的话。
    我们如果每次再上课的时候要配置该IP地址,记忆起来就比较的麻烦。
    所以,为了方便表示IP地址,我们就把IP地址的每一个字节上的数据换算成十进制,然后用.分开来表示:
    既"点分十进制"

    b:IP地址的组成    

    网络号段+主机号段
    A类:第一号段为网络号段+后三段的主机号段
    一个网络号:256*256*256 = 16777216
    B类:前二号段为网络号段+后二段的主机号段
    一个网络号:256*256 = 65536
    C类:前三号段为网络号段+后一段的主机号段
    一个网络号:256

    c:IP地址的分类

    A类 1.0.0.1---127.255.255.254

    (1)10.X.X.X是私有地址(私有地址就是在互联网上不使用,而被用在局域网络中的地址)

    (2)127.X.X.X是保留地址,用做循环测试用的。
    B类 128.0.0.1---191.255.255.254172.16.0.0---172.31.255.255是私有地址。169.254.X.X是保留地址。
    C类 192.0.0.1---223.255.255.254192.168.X.X是私有地址
    D类 224.0.0.1---239.255.255.254
    E类 240.0.0.1---247.255.255.254

    特殊的IP地址:
    127.0.0.1 回环地址(表示本机)
    x.x.x.255 广播地址
    x.x.x.0 网络地址

    d:dos命令

    ipconfig 查看本机ip地址
    ping 后面跟ip地址。测试本机与指定的ip地址间的通信是否有问题

    e:InetAddress

    * 看InetAddress的成员方法:
     * public static InetAddress getByName(String host):根据主机名或者IP地址的字符串表示得到IP地址对象(此方法为单例设计模式)
     */

    public class InetAddressDemo {
    	public static void main(String[] args) throws UnknownHostException {
    		// public static InetAddress getByName(String host)
    		// InetAddress address = InetAddress.getByName("liuyi");
    		// InetAddress address = InetAddress.getByName("192.168.12.92");
    		InetAddress address = InetAddress.getByName("192.168.12.63");
    
    		// 获取两个东西:主机名,IP地址
    		// public String getHostName()
    		String name = address.getHostName();
    		// public String getHostAddress()
    		String ip = address.getHostAddress();
    		System.out.println(name + "---" + ip);
    	}
    }


    B:端口


    是应用程序的标识。范围:0-65535。其中0-1024不建议使用为系统保留端口。


    C:协议:        通信的规则


    UDP:数据打包,有限制,不连接,效率高,不可靠
    TCP:建立数据通道,无限制,效率低,可靠

    (3)Socket机制

    A:通信两端都应该有Socket对象

    B:所有的通信都是通过Socket间的IO进行操作的


    (4)UDP协议发送和接收数据(掌握 )


    发送:
    创建UDP发送端的Socket对象
    创建数据并把数据打包
    发送数据

    释放资源

    import java.io.IOException;
    import java.net.DatagramPacket;
    import java.net.DatagramSocket;
    import java.net.InetAddress;
    /*
     * UDP协议发送数据:
     * A:创建发送端Socket对象
     * B:创建数据,并把数据打包
     * C:调用Socket对象的发送方法发送数据包
     * D:释放资源
     */
    public class SendDemo {
    	public static void main(String[] args) throws IOException {
    		// 创建发送端Socket对象
    		// DatagramSocket()
    		DatagramSocket ds = new DatagramSocket();
    
    		// 创建数据,并把数据打包
    		// DatagramPacket(byte[] buf, int length, InetAddress address, int port)
    		// 创建数据
    		byte[] bys = "hello,udp,我来了".getBytes();
    		// 长度
    		int length = bys.length;
    		// IP地址对象
    		InetAddress address = InetAddress.getByName("192.168.12.92");
    		// 端口
    		int port = 10086;
    		DatagramPacket dp = new DatagramPacket(bys, length, address, port);
    
    		// 调用Socket对象的发送方法发送数据包
    		// public void send(DatagramPacket p)
    		ds.send(dp);
    
    		// 释放资源
    		ds.close();
    	}
    }
    



    接收:
    创建UDP接收端的Socket对象
    创建数据包用于接收数据
    接收数据
    解析数据包

    释放资源

    import java.io.IOException;
    import java.net.DatagramPacket;
    import java.net.DatagramSocket;
    import java.net.InetAddress;
    
    /*
     * UDP协议接收数据:
     * A:创建接收端Socket对象
     * B:创建一个数据包(接收容器)
     * C:调用Socket对象的接收方法接收数据
     * D:解析数据包,并显示在控制台
     * E:释放资源
     */
    public class ReceiveDemo {
    	public static void main(String[] args) throws IOException {
    		// 创建接收端Socket对象
    		// DatagramSocket(int port)
    		DatagramSocket ds = new DatagramSocket(10086);
    
    		// 创建一个数据包(接收容器)
    		// DatagramPacket(byte[] buf, int length)
    		byte[] bys = new byte[1024];
    		int length = bys.length;
    		DatagramPacket dp = new DatagramPacket(bys, length);
    
    		// 调用Socket对象的接收方法接收数据
    		// public void receive(DatagramPacket p)
    		ds.receive(dp); // 阻塞式
    
    		// 解析数据包,并显示在控制台
    		// 获取对方的ip
    		// public InetAddress getAddress()
    		InetAddress address = dp.getAddress();
    		String ip = address.getHostAddress();
    		// public byte[] getData():获取数据缓冲区
    		// public int getLength():获取数据的实际长度
    		byte[] bys2 = dp.getData();
    		int len = dp.getLength();
    		String s = new String(bys2, 0, len);
    		System.out.println(ip + "传递的数据是:" + s);
    
    		// 释放资源
    		ds.close();
    	}
    }
    


    (5)TCP协议发送和接收数据(掌握 )


    发送:
    创建TCP客户端的Socket对象
    获取输出流,写数据
    释放资源
    import java.io.IOException;
    import java.io.OutputStream;
    import java.net.Socket;
    
    /*
     * TCP协议发送数据:
     * A:创建发送端的Socket对象
     * 		这一步如果成功,就说明连接已经建立成功了。
     * B:获取输出流,写数据
     * C:释放资源
     * 
     * 连接被拒绝。TCP协议一定要先看服务器。
     * java.net.ConnectException: Connection refused: connect
     */
    public class ClientDemo {
    	public static void main(String[] args) throws IOException {
    		// 创建发送端的Socket对象
    		// Socket(InetAddress address, int port)
    		// Socket(String host, int port)
    		// Socket s = new Socket(InetAddress.getByName("192.168.12.92"), 8888);
    		Socket s = new Socket("192.168.12.92", 8888);
    
    		// 获取输出流,写数据
    		// public OutputStream getOutputStream()
    		OutputStream os = s.getOutputStream();
    		os.write("hello,tcp,我来了".getBytes());
    
    		// 释放资源
    		s.close();
    	}
    }
    


    接收:
    创建TCP服务器端的Socket对象
    监听客户端连接
    获取输入流,读取数据

    释放资源

    import java.io.IOException;
    import java.io.InputStream;
    import java.net.ServerSocket;
    import java.net.Socket;
    
    /*
     * TCP协议接收数据:
     * A:创建接收端的Socket对象
     * B:监听客户端连接。返回一个对应的Socket对象
     * C:获取输入流,读取数据显示在控制台
     * D:释放资源
     */
    public class ServerDemo {
    	public static void main(String[] args) throws IOException {
    		// 创建接收端的Socket对象
    		// ServerSocket(int port)
    		ServerSocket ss = new ServerSocket(8888);
    
    		// 监听客户端连接。返回一个对应的Socket对象
    		// public Socket accept()
    		Socket s = ss.accept(); // 侦听并接受到此套接字的连接。此方法在连接传入之前一直阻塞。
    
    		// 获取输入流,读取数据显示在控制台
    		InputStream is = s.getInputStream();
    
    		byte[] bys = new byte[1024];
    		int len = is.read(bys); // 阻塞式方法
    		String str = new String(bys, 0, len);
    
    		String ip = s.getInetAddress().getHostAddress();
    
    		System.out.println(ip + "---" + str);
    
    		// 释放资源
    		s.close();
    		// ss.close(); //这个不应该关闭
    	}
    }
    


    (6)案例:
    A:UDP
    a:最基本的UDP协议发送和接收数据
    b:把发送数据改进为键盘录入
    c:一个简易聊天小程序并用多线程改进
    B:TCP
    a:最基本的TCP协议发送和接收数据
    b:服务器给出反馈
    c:客户端键盘录入服务器控制台输出
    d:客户端键盘录入服务器写到文本文件
    e:客户端读取文本文件服务器控制台输出

    f:客户端读取文本文件服务器写到文本文件

    client

    import java.io.BufferedReader;
    import java.io.BufferedWriter;
    import java.io.FileReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.OutputStreamWriter;
    import java.net.Socket;
    
    /*
     * 按照我们正常的思路加入反馈信息,结果却没反应。为什么呢?
     * 读取文本文件是可以以null作为结束信息的,但是呢,通道内是不能这样结束信息的。
     * 所以,服务器根本就不知道你结束了。而你还想服务器给你反馈。所以,就相互等待了。
     * 
     * 如何解决呢?
     * A:在多写一条数据,告诉服务器,读取到这条数据说明我就结束,你也结束吧。
     * 		这样做可以解决问题,但是不好。
     * B:Socket对象提供了一种解决方案
     * 		public void shutdownOutput()
     */
    
    public class UploadClient {
    	public static void main(String[] args) throws IOException {
    		// 创建客户端Socket对象
    		Socket s = new Socket("192.168.12.92", 11111);
    
    		// 封装文本文件
    		BufferedReader br = new BufferedReader(new FileReader(
    				"InetAddressDemo.java"));
    		// 封装通道内流
    		BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(
    				s.getOutputStream()));
    
    		String line = null;
    		while ((line = br.readLine()) != null) { // 阻塞
    			bw.write(line);
    			bw.newLine();
    			bw.flush();
    		}
    		
    		//自定义一个结束标记
    //		bw.write("over");
    //		bw.newLine();
    //		bw.flush();
    		
    		//Socket提供了一个终止,它会通知服务器你别等了,我没有数据过来了
    		s.shutdownOutput();
    
    		// 接收反馈
    		BufferedReader brClient = new BufferedReader(new InputStreamReader(
    				s.getInputStream()));
    		String client = brClient.readLine(); // 阻塞
    		System.out.println(client);
    
    		// 释放资源
    		br.close();
    		s.close();
    	}
    }
    
    Sever

    import java.io.BufferedReader;
    import java.io.BufferedWriter;
    import java.io.FileWriter;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.OutputStreamWriter;
    import java.net.ServerSocket;
    import java.net.Socket;
    
    public class UploadServer {
    	public static void main(String[] args) throws IOException {
    		// 创建服务器端的Socket对象
    		ServerSocket ss = new ServerSocket(11111);
    
    		// 监听客户端连接
    		Socket s = ss.accept();// 阻塞
    
    		// 封装通道内的流
    		BufferedReader br = new BufferedReader(new InputStreamReader(
    				s.getInputStream()));
    		// 封装文本文件
    		BufferedWriter bw = new BufferedWriter(new FileWriter("Copy.java"));
    
    		String line = null;
    		while ((line = br.readLine()) != null) { // 阻塞
    		// if("over".equals(line)){
    		// break;
    		// }
    			bw.write(line);
    			bw.newLine();
    			bw.flush();
    		}
    
    		// 给出反馈
    		BufferedWriter bwServer = new BufferedWriter(new OutputStreamWriter(
    				s.getOutputStream()));
    		bwServer.write("文件上传成功");
    		bwServer.newLine();
    		bwServer.flush();
    
    		// 释放资源
    		bw.close();
    		s.close();
    	}
    }
    



    g:上传图片

    Client

    import java.io.BufferedInputStream;
    import java.io.BufferedOutputStream;
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.net.Socket;
    
    public class UploadClient {
    	public static void main(String[] args) throws IOException {
    		// 创建客户端Socket对象
    		Socket s = new Socket("192.168.12.92", 19191);
    
    		// 封装图片文件
    		BufferedInputStream bis = new BufferedInputStream(new FileInputStream(
    				"林青霞.jpg"));
    		// 封装通道内的流
    		BufferedOutputStream bos = new BufferedOutputStream(s.getOutputStream());
    
    		byte[] bys = new byte[1024];
    		int len = 0;
    		while ((len = bis.read(bys)) != -1) {
    			bos.write(bys, 0, len);
    			bos.flush();
    		}
    		
    		s.shutdownOutput();
    
    		// 读取反馈
    		InputStream is = s.getInputStream();
    		byte[] bys2 = new byte[1024];
    		int len2 = is.read(bys2);
    		String client = new String(bys2, 0, len2);
    		System.out.println(client);
    
    		// 释放资源
    		bis.close();
    		s.close();
    	}
    }
    
    Server

    import java.io.BufferedInputStream;
    import java.io.BufferedOutputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.OutputStream;
    import java.net.ServerSocket;
    import java.net.Socket;
    
    public class UploadServer {
    	public static void main(String[] args) throws IOException {
    		// 创建服务器Socket对象
    		ServerSocket ss = new ServerSocket(19191);
    
    		// 监听客户端连接
    		Socket s = ss.accept();
    
    		// 封装通道内流
    		BufferedInputStream bis = new BufferedInputStream(s.getInputStream());
    		// 封装图片文件
    		BufferedOutputStream bos = new BufferedOutputStream(
    				new FileOutputStream("mn.jpg"));
    
    		byte[] bys = new byte[1024];
    		int len = 0;
    		while ((len = bis.read(bys)) != -1) {
    			bos.write(bys, 0, len);
    			bos.flush();
    		}
    
    		// 给一个反馈
    		OutputStream os = s.getOutputStream();
    		os.write("图片上传成功".getBytes());
    
    		bos.close();
    		s.close();
    	}
    }
    



    h:多线程改进上传文件

    Server

    import java.io.IOException;
    import java.net.ServerSocket;
    import java.net.Socket;
    
    public class UploadServer {
    	public static void main(String[] args) throws IOException {
    		// 创建服务器Socket对象
    		ServerSocket ss = new ServerSocket(11111);
    
    		while (true) {
    			Socket s = ss.accept();
    			new Thread(new UserThread(s)).start();
    		}
    	}
    }
    
    Thread

    import java.io.BufferedReader;
    import java.io.BufferedWriter;
    import java.io.FileReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.OutputStreamWriter;
    import java.net.Socket;
    
    public class UploadClient {
    	public static void main(String[] args) throws IOException {
    		// 创建客户端Socket对象
    		Socket s = new Socket("192.168.12.92", 11111);
    
    		// 封装文本文件
    		// BufferedReader br = new BufferedReader(new FileReader(
    		// "InetAddressDemo.java"));
    		BufferedReader br = new BufferedReader(new FileReader(
    				"ReceiveDemo.java"));
    		// 封装通道内流
    		BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(
    				s.getOutputStream()));
    
    		String line = null;
    		while ((line = br.readLine()) != null) { // 阻塞
    			bw.write(line);
    			bw.newLine();
    			bw.flush();
    		}
    
    		// Socket提供了一个终止,它会通知服务器你别等了,我没有数据过来了
    		s.shutdownOutput();
    
    		// 接收反馈
    		BufferedReader brClient = new BufferedReader(new InputStreamReader(
    				s.getInputStream()));
    		String client = brClient.readLine(); // 阻塞
    		System.out.println(client);
    
    		// 释放资源
    		br.close();
    		s.close();
    	}
    }
    


    展开全文
  • 通过流发送消息非常简单,只需要创建消息...为了对发送接收过程进行展示,我们考虑投票服务的如下几点:1)维护一个候选人ID与其获得选票数的映射,2)记录提交的投票,3)根据其获得的选票数,对查询指定的候选人

    通过流发送消息非常简单,只需要创建消息,调用toWire()方法,添加适当的成帧信息,再写入流。当然,接收消息就要按照相反的顺序执行。这个过程适用于TCP协议,而对于UDP协议,不需要显式地成帧,因为UDP协议中保留了消息的边界信息。为了对发送与接收过程进行展示,我们考虑投票服务的如下几点:1)维护一个候选人ID与其获得选票数的映射,2)记录提交的投票,3)根据其获得的选票数,对查询指定的候选人和为其投票的消息做出响应。首先,我们实现一个投票服务器所用到的服务。当接收到投票消息时,投票服务器将调用VoteService类的handleRequest() 方法对请求进行处理。

    VoteService.java

    0 import java.util.HashMap;

    1 import java.util.Map;

    2

    3 public class VoteService {

    4

    5 // Map of candidates to number of votes

    6 private Map<Integer, Long> results = new

    HashMap<Integer, Long>();

    7

    8 public VoteMsg handleRequest(VoteMsg msg) {

    9 if (msg.isResponse()) { // If response, just send it back

    10 return msg;

    11 }

    12 msg.setResponse(true); // Make message a response

    13 // Get candidate ID and vote count

    14 int candidate = msg.getCandidateID();

    15 Long count = results.get(candidate);

    16 if (count == null) {

    17 count = 0L; // Candidate does not exist

    18 }

    19 if (!msg.isInquiry()) {

    20 results.put(candidate, ++count); // If vote, increment

    count

    21 }

    22 msg.setVoteCount(count);

    23 return msg;

    24 }

    25 }

     

     VoteService.java

     1.创建候选人ID与选票数量的映射:第6

    对于查询请求,给定的候选人ID用来在映射中查询其获得的选票数量。对于投票请求,增加后的选票数又存回映射。

     2.handleRequest():第8-24

     返回响应:第9-12

     如果投票消息已经是一个响应信息,则直接发回而不对其进行处理和修改。否则,对其响应消息标志进行设置。

    查找当前获得的选票总数:第13-18

     根据候选人ID从映射中获取其获得的选票总数。如果该候选人ID在映射中不存在,则将其获得的选票数设为0.

     如果有新的投票,则更新选票总数:第19-21

     如果之前候选人不存在,则创建新的映射,否则,只是简单地修改已有的映射。

     设置选票总数并返回消息:第22-23

     下面我们将展示如何实现一个TCP投票客户端,该客户端通过TCP套接字连接到投票服务器,在一次投票后发送一个查询请求,并接收查询和投票结果。

     VoteClientTCP.java

    0 import java.io.OutputStream;

    1 import java.net.Socket;

    2

    3 public class VoteClientTCP {

    4

    5 public static final int CANDIDATEID = 888;

    6

    7 public static void main(String args[]) throws Exception

    {

    8

    9 if (args.length != 2) { // Test for correct # of args

    10 throw new IllegalArgumentException("Parameter(s):

    <Server> <Port>");

    11 }

    12

    13 String destAddr = args[0]; // Destination address

    14 int destPort = Integer.parseInt(args[1]); //

    Destination port

    15

    16 Socket sock = new Socket(destAddr, destPort);

    17 OutputStream out = sock.getOutputStream();

    18

    19 // Change Bin to Text for a different framing strategy

    20 VoteMsgCoder coder = new VoteMsgBinCoder();

    21 // Change Length to Delim for a different encoding

    strategy

    22 Framer framer = new

    LengthFramer(sock.getInputStream());

    23

    24 // Create an inquiry request (2nd arg = true)

    25 VoteMsg msg = new VoteMsg(false, true, CANDIDATEID, 0);

    26 byte[] encodedMsg = coder.toWire(msg);

    27

    28 // Send request

    29 System.out.println("Sending Inquiry (" +

    encodedMsg.length + " bytes): ");

    30 System.out.println(msg);

    31 framer.frameMsg(encodedMsg, out);

    32

    33 // Now send a vote

    34 msg.setInquiry(false);

    35 encodedMsg = coder.toWire(msg);

    36 System.out.println("Sending Vote (" +

    encodedMsg.length + " bytes): ");

    37 framer.frameMsg(encodedMsg, out);

    38

    39 // Receive inquiry response

    40 encodedMsg = framer.nextMsg();

    41 msg = coder.fromWire(encodedMsg);

    42 System.out.println("Received Response (" +

    encodedMsg.length

    43 + " bytes): ");

    44 System.out.println(msg);

    45

    46 // Receive vote response

    47 msg = coder.fromWire(framer.nextMsg());

    48 System.out.println("Received Response (" +

    encodedMsg.length

    49 + " bytes): ");

    50 System.out.println(msg);

    51

    52 sock.close();

    53 }

    54 }

     

     VoteClientTCP.java

     1.参数处理:第9-14

     2.创建套接字,获取输出流:第16-17

     3.创建二进制编码器和基于长度的成帧器:第20-22

    我们将使用一个编码器对投票消息进行编码和解码,这里为我们的协议选择的是二进制编码器。其次,由于TCP协议是一个基于流的服务,我们需要提供字节的帧。在此,我们使用LengthFramer类,它为每条消息添加一个长度前缀。注意,我们只需要改变具体的类,就能方便地转换成基于定界符的成帧方法和基于文本的编码方式,这里将VoteMsgCoderFramer换成VoteMsgTextCoderDelimFramer即可。 

    4.创建和发送消息:第24-37 

    创建,编码,成帧和发送查询请求,后面是为相同候选人的投票消息。

     5.获取和解析响应:第39-50

     我们使用nextMsg()方法用于返回下一条编码后的消息,并通过fromWire()方法对其进行解析/解码。

    6.关闭套接字:第52

    下面我们示范TCP版本的投票服务器。该服务器反复地接收新的客户端连接,并使用VoteService类为客户端的投票消息作出响应。

     VoteServerTCP.java

    0 import java.io.IOException;

    1 import java.net.ServerSocket;

    2 import java.net.Socket;

    3

    4 public class VoteServerTCP {

    5

    6 public static void main(String args[]) throws Exception {

    7

    8 if (args.length != 1) { // Test for correct # of args

    9 throw new IllegalArgumentException("Parameter(s): <Port>");

    10 }

    11

    12 int port = Integer.parseInt(args[0]); // Receiving Port

    13

    14 ServerSocket servSock = new ServerSocket(port);

    15 // Change Bin to Text on both client and server for different encoding

    16 VoteMsgCoder coder = new VoteMsgBinCoder();

    17 VoteService service = new VoteService();

    18

    19 while (true) {

    20 Socket clntSock = servSock.accept();

    21 System.out.println("Handling client at " + clntSock.

    getRemoteSocketAddress());

    22 // Change Length to Delim for a different framing strategy

    23 Framer framer = new LengthFramer(clntSock.getInputStream());

    24 try {

    25 byte[] req;

    26 while ((req = framer.nextMsg()) != null) {

    27 System.out.println("Received message (" + req.length + " bytes)");

    28 VoteMsg responseMsg = service.handleRequest(coder.fromWire(req));

    29 framer.frameMsg(coder.toWire(responseMsg), clntSock.getOutputStream());

    30 }

    31 } catch (IOException ioe) {

    32 System.err.println("Error handling client: " + ioe.getMessage());

    33 } finally {

    34 System.out.println("Closing connection");

    35 clntSock.close();

    36 }

    37 }

    38 }

    39 }

     

    VoteServerTCP.java

    1.为服务器端建立编码器和投票服务:第15-17

    2.反复地接收和处理客户端连接:第19-37

    接收新的客户端,打印客户端地址:第20-21

    为客户端创建成帧器:第23

    从客户端获取消息并对其解码:第26-28

    反复地向成帧器发送获取下一条消息的请求,直到其返回null,即指示了消息的结束。

    处理消息,发送响应信息:第28-29

    将解码后的消息传递给投票服务,以进行下一步处理。编码,成帧和回发响应消息。

    UDP版本的投票客户端与TCP版本非常相似。需要注意的是,在UDP客户端中我们不需要使用成帧器,因为UDP协议为我们维护了消息的边界信息。对于UDP协议,我们使用基于文本的编码方式对消息进行编码,不过只要客户端与服务器能达成一致,也能够很方便地改成其他编码方式。

     

    VoteClientUDP.java

    0 import java.io.IOException;

    1 import java.net.DatagramPacket;

    2 import java.net.DatagramSocket;

    3 import java.net.InetAddress;

    4 import java.util.Arrays;

    5

    6 public class VoteClientUDP {

    7

    8 public static void main(String args[]) throws

    IOException {

    9

    10 if (args.length != 3) { // Test for correct # of args

    11 throw new IllegalArgumentException("Parameter(s):

    <Destination>" +

    12 " <Port> <Candidate#>");

    13 }

    14

    15 InetAddress destAddr = InetAddress.getByName(args[0]);

    // Destination addr

    16 int destPort = Integer.parseInt(args[1]); //

    Destination port

    17 int candidate = Integer.parseInt(args[2]); // 0 <=

    candidate <= 1000 req'd

    18

    19 DatagramSocket sock = new DatagramSocket(); // UDP

    socket for sending

    20 sock.connect(destAddr, destPort);

    21

    22 // Create a voting message (2nd param false = vote)

    23 VoteMsg vote = new VoteMsg(false, false, candidate, 0);

    24

    25 // Change Text to Bin here for a different coding strategy

    26 VoteMsgCoder coder = new VoteMsgTextCoder();

    27

    28 // Send request

    29 byte[] encodedVote = coder.toWire(vote);

    30 System.out.println("Sending Text-Encoded Request (" +

    encodedVote.length

    31 + " bytes): ");

    32 System.out.println(vote);

    33 DatagramPacket message = new

    DatagramPacket(encodedVote, encodedVote.length);

    34 sock.send(message);

    35

    36 // Receive response

    37 message = new DatagramPacket(new

    byte[VoteMsgTextCoder.MAX_WIRE_LENGTH],

    38 VoteMsgTextCoder.MAX_WIRE_LENGTH);

    39 sock.receive(message);

    40 encodedVote = Arrays.copyOfRange(message.getData(), 0,

    message.getLength());

    41

    42 System.out.println("Received Text-Encoded Response ("

    + encodedVote.length

    43 + " bytes): ");

    44 vote = coder.fromWire(encodedVote);

    45 System.out.println(vote);

    46 }

    47 }

     

     VoteClientUDP.java

     1.设置DatagramSocket      和连接:第10-20 

    通过调用connect()方法,我们不必1)为发送的每个数据报文指定远程地址和端口,也不必2)测试接收到的每个数据报文的源地址。

     2.创建选票和编码器:第22-26

     这次使用的是文本编码器,但我们也可以很容易地换成二进制编码器。注意这里我们不需要成帧器,因为只要每次发送都只有一个投票消息,UDP协议就已经为我们保留了边界信息。

    3.向服务器发送请求消息:第28-34

    4.接收,解码和打印服务器响应信息:第36-45

    在创建DatagramPacket时,我们需要知道消息的最大长度,以避免数据被截断。当然,在对数据报文进行解码时,我们只使用数据报文中包含的实际字节,因此调用了Arrays.copyOfRange()方法来复制返回的数据报文中数组的子序列。

    最后是UDP投票服务器,同样,也与TCP版本非常相似。

     VoteServerUDP.java

    0 import java.io.IOException;

    1 import java.net.DatagramPacket;

    2 import java.net.DatagramSocket;

    3 import java.util.Arrays;

    4

    5 public class VoteServerUDP {

    6

    7 public static void main(String[] args) throws

    IOException {

    8

    9 if (args.length != 1) { // Test for correct # of args

    10 throw new IllegalArgumentException("Parameter(s):

    <Port>");

    11 }

    12

    13 int port = Integer.parseInt(args[0]); // Receiving Port

    14

    15 DatagramSocket sock = new DatagramSocket(port); //

    Receive socket

    16

    17 byte[] inBuffer = new

    byte[VoteMsgTextCoder.MAX_WIRE_LENGTH];

    18 // Change Bin to Text for a different coding approach

    19 VoteMsgCoder coder = new VoteMsgTextCoder();

    20 VoteService service = new VoteService();

    21

    22 while (true) {

    23 DatagramPacket packet = new DatagramPacket(inBuffer,

    inBuffer.length);

    24 sock.receive(packet);

    25 byte[] encodedMsg =

    Arrays.copyOfRange(packet.getData(), 0,

    packet.getLength());

    26 System.out.println("Handling request from " +

    packet.getSocketAddress() + " ("

    27 + encodedMsg.length + " bytes)");

    28

    29 try {

    30 VoteMsg msg = coder.fromWire(encodedMsg);

    31 msg = service.handleRequest(msg);

    32 packet.setData(coder.toWire(msg));

    33 System.out.println("Sending response (" +

    packet.getLength() + " bytes):");

    34 System.out.println(msg);

    35 sock.send(packet);

    36 } catch (IOException ioe) {

    37 System.err.println("Parse error in message: " +

    ioe.getMessage());

    38 }

    39 }

    40 }

    41 }

     

    VoteServerUDP.java

     1.设置:第17-20

    为服务器创建接收缓存区,编码器,以及投票服务。

    2.反复地接收和处理客户端的投票消息:第22-39

    为接收数据报文创建DatagramPacket:第23

    在每次迭代中将数据区重置为输入缓存区。

    接收数据报文,抽取数据:第24-25

    UDP替我们完成了成帧的工作!

    解码和处理请求:第30-31

    服务将响应返回给消息。

    编码并发送响应消息:第32-35

     

    相关下载:

    Java_TCPIP_Socket编程(doc)

    http://download.csdn.net/detail/undoner/4940239

     

    文献来源:

    UNDONER(小杰博客) :http://blog.csdn.net/undoner

    LSOFT.CN(琅软中国) :http://www.lsoft.cn

     

    展开全文
  • java-TCP协议发送和接收数据

    千次阅读 2018-07-22 00:36:00
    java-TCP协议发送和接收数据 TCP协议接收数据的步骤: A:创建接收数据的Socket对象  创建对象的时候要指定端口 B:监听客户端连接  等待客户端连接 C:获取Socket对象的输入流(字节流) D:读数据,...
  • 发送和接收电子邮件时的相关协议以及流程 1.SMTP协议 2.POP3协议 3.IMAP协议
  • 多线程实现UDP协议发送和接收

    千次阅读 2015-12-13 12:48:48
    package 多线程实现UDP协议发送和接收; import java.io.IOException; import java.net.DatagramSocket; /*  * 通过多线程改进刚才的聊天程序,这样我就可以实现在一个窗口发送和接收数据了  */ ...
  • UDP协议发送和接收消息案例详解

    千次阅读 2016-09-10 16:49:43
    将UDP工程分两个包: 发送方包(sender)和接收方包(receiver) 发送方包(sender)定义一个发送方类(Sender);接收方包(receiver)定义一个接收方类(Sender); 发送方(sender)类需要定义四个变量:
  • 这是我精力整理的ActiveMQ发送和接收protobuf协议消息的实例。 也对ActiveMQ进行了简化封装,也配置了自动重连机制,亲测可用!
  • 使用Socket结合SMTP/POP3邮件协议发送和接收邮件
  • python Tcp协议发送和接收信息

    千次阅读 2018-10-10 16:59:19
    需要建立2个文件,一个作为客户端,一个作为服务端 文件一 作为客户端client,文件二作为...# SOCK_STREAM---TCP协议方式 # AF_INET----我的是ipv4地址 #1,创建socket对象:指定传输协议 s=socket.socket(socke...
  • 今天做一个客户端和服务器,客户端可以发送和接收信息,服务器也可以同时发送信息和接收信息 直接上代码 package Test; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io....
  • 在工作中有涉及用Java实现UDP协议传输和接收数据,因为之前学习网络编程的时候这块没怎么认真关注,这里补充记录下。 UDP协议发送数据 public class UdpSendDemo { public static void main(String[] args) { //...
  • python Tcp协议循环发送和接收

    千次阅读 2018-10-10 20:04:14
    需要建立2个文件,一个作为客户端,一个作为服务端...# 创建socket对象:指定传输协议 # AF_INET---ipv4 # SOCK_STREAM---TCP协议 import socket s=socket.socket(socket.AF_INET,socket.SOCK_STREAM) # 建立连接---...
  • User Datagram Protocol :用户数据包协议1.1 UDP特点面向无连接的协议发送端只管发送,不管接收端是否存在,同样接收端收到数据时,也不会向发送端反馈是否收到数据.发送数据大小限制在64KB以内.基于数据包传输数据:要...
  • UDP是基于数据报文的传输协议,面向无连接,不可靠,下面介绍发送和接收的Demo: 发送程序:import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io....
  • TCP协议发送数据 public class TcpSendDemo { public static void main(String[] args) { // TODO Auto-generated method stub Socket s=null; OutputStream os=null; try { s=new Socke...
  • 需要用C#http协议发送和接收数据,没积分了,CSDN上的源码下不来,发篇日记能得积分吗?一分也行啊。
  • python UDP(udp)协议发送和接收

    万次阅读 2018-10-10 18:18:14
    需要建立2个文件,一个作为客户端,一个作为服务端 文件一 作为客户端client,文件二作为服务端server udp的特点是不需要建立连接 文件一客户端 ...s=socket.socket(socket.AF_INET,socket....#发送数据 字节 ...
  • 我们使用邮件一般是使用邮件客户端,比如,Thunderbird,Foxmail,Microsoft Outlook等等,使用的时候需要设置STMP发送服务器,POP3或者IMAP接收服务器这样给我们的印象似乎是STMP是发送协议,POP3或者IMAP是接收协议。...
  • 使用UDP协议发送和接收数据

    千次阅读 2013-09-04 08:44:50
    首选引用以下两个: using System.Net; using System.Net.Sockets; //获取机机IP地址: IPHostEntry ihe = Dns.GetHostByName(Dns.GetHostName());...IPAddress myself = ihe....//发送消息 UdpClient udpClient = new
  • MFC实现的窗口程序,集成了发送和接收RTP包的功能,接收到的视频用FFmpeg解码并显示出来。该例子代码对应我博客上的一篇文章:https://blog.csdn.net/zhoubotong2012/article/details/86510032
  • HTTP协议使用JSON发送和接收数据

    千次阅读 2018-06-07 19:08:00
    public static JSONObject httpInterfaceForJson(String requestUrl, String requestMethod, JSONObject fullJson) { String res = ""; StringBuffer buffer = new StringBuffer(); HttpURL...
  • 数据协议发送接收

    2018-04-27 08:52:59
    最近在使用UWB与飞控进行数据通信的过程中,发现一些丢包现象,为此对协议接收进行总结。发送协议设计:首先找到UWB project中串口发送缓存区,以本项目为例,待发送的数据都是存在下面u8类型数组中u8 SendBuff...

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 15,915
精华内容 6,366
关键字:

发送和接收协议