- #include <Winsock2.h>
- #include <stdio.h>
- void main()
- {
- WORD wVersionRequested;
- WSADATA wsaData;
- int err;
- wVersionRequested = MAKEWORD( 2, 2 );
- err = WSAStartup( wVersionRequested,&wsaData);
- if( err != 0){
- return;
- }
- if( LOBYTE( wsaData.wVersion)!= 2||
- HIBYTE(wsaData.wVersion)!= 2)
- {
- WSACleanup();
- return;
- }
- //SOCKET sockClient = socket(AF_INET,SOCK_STREAM,0);
- SOCKADDR_IN addrSrv;
- addrSrv.sin_addr.S_un.S_addr = inet_addr("10.150.20.45");
- addrSrv.sin_family = AF_INET;
- addrSrv.sin_port = htons(6000);
- SOCKET sockClient;
- sockClient = socket(AF_INET,SOCK_STREAM,0);
- connect(sockClient,(SOCKADDR*)&addrSrv,sizeof(SOCKADDR));
- for(int i=0;i<30;i++)
- {
- //char recvBuf[100];
- //recv(sockClient,recvBuf,100,0);
- //printf("%s/n",recvBuf);
- try{
- send(sockClient,"This",strlen("This"),0);
- }catch(...)
- {
- printf("%s/n","Errors");
- sockClient = socket(AF_INET,SOCK_STREAM,0);
- connect(sockClient,(SOCKADDR*)&addrSrv,sizeof(SOCKADDR));
- }
- Sleep(500);
- }
- closesocket(sockClient);
- WSACleanup();
- //Sleep(10000);
- return;
- }
vc++的程序在VS2008运行,还需要增加一个lib #pragma comment(lib, "ws2_32.lib") 我在在编译器加 或者直接加到代码中,
程序强调,一次连接,持续发送数据,所有对一些细节如多个客户端连接的处理,没有涉及,我还有些疑问就是,发送字节不定长的处理。
- #include <Winsock2.h>
- #include <stdio.h>
- void main()
- {
- WORD wVersionRequested;
- WSADATA wsaData;
- int err;
- wVersionRequested = MAKEWORD( 2, 2 );
- err = WSAStartup( wVersionRequested,&wsaData);
- if( err != 0){
- return;
- }
- if( LOBYTE( wsaData.wVersion)!= 2||
- HIBYTE(wsaData.wVersion)!= 2)
- {
- WSACleanup();
- return;
- }
- SOCKET sockSrv = socket(AF_INET,SOCK_STREAM,0);
- SOCKADDR_IN addrSrv;
- addrSrv.sin_addr.S_un.S_addr = htonl(INADDR_ANY);
- addrSrv.sin_family = AF_INET;
- addrSrv.sin_port= htons(6000);
- bind(sockSrv,(SOCKADDR*)&addrSrv,sizeof(SOCKADDR));
- err = listen(sockSrv,5);
- if(err!=0)
- {
- //getErrors
- err = WSAGetLastError();
- }
- SOCKADDR_IN addrClient;
- int len = sizeof(SOCKADDR);
- SOCKET sockConn = accept(sockSrv,(SOCKADDR*)&addrClient,&len);
- while(1)
- {
- //char sendBuf[100];
- //sprintf_s(sendBuf,"Welcome %s to http://www.sunxin.org",
- // inet_ntoa(addrClient.sin_addr));
- //send(sockConn,sendBuf,strlen(sendBuf)+1,0);
- char recvBuf[4];
- int sign = recv(sockConn,recvBuf,4,0);
- printf("%s/n",recvBuf);
- }
- closesocket(sockConn);
- return;
- }
下面是java实现的,源程序
- package coldwind.socket.Server;
- import java.net.*;
- import java.io.*;
- import eccl.socket.tools.*;
- public class TcpServer{
- public static void main(String[] args) throws Exception{
- ServerSocket ss = new ServerSocket(6000);
- Socket s = new Socket();
- System.out.println ("start");
- s = ss.accept();
- System.out.println("A client has heen connected.");
- DataInputStream r = new DataInputStream(s.getInputStream());
- int count=0;
- while(true){
- try {
- //Thread.sleep(10);
- byte c = 0;
- byte[] sendType = new byte[128];
- // if(r.read()<=0)
- // continue;
- Thread.sleep(100);
- for(int i=0;i<4;i++){
- c = r.readByte();
- sendType[i]=c;
- }
- System.out.println ("count:"+count);
- count++;
- System.out.println ("sendType: "+ByteOperator.getStr(sendType,0,4));
- }
- catch(EOFException eof)
- {
- continue;
- }
- catch (Exception ex) {
- s.close();
- System.out.println (ex.toString());
- continue;
- }
- }
- }
- }
- package coldwind.socket.Client;
- import java.net.*;
- import java.io.*;
- import java.sql.Connection;
- import java.sql.DriverManager;
- import java.sql.Statement;
- import eccl.socket.tools.ByteOperator;
- /**
- * 发送实时数据包类
- */
- public class TcpClient{
- public TcpClient(){
- }
- private static String ip = "127.0.0.1";
- private static int port = 6000;
- public static Socket socket = null;
- public static BufferedOutputStream bufos = null;
- public static boolean isException = false;//是否有异常
- public static String errors = "";
- /**
- * 获得与TcpServer的连接
- */
- public static void socketClose(){
- try {
- if(socket!=null){
- if(!socket.isClosed())
- socket.close();
- }
- } catch (IOException e) {
- // TODO 自动生成 catch 块
- e.printStackTrace();
- }
- }
- //进行连接
- public static void getTcpSocket(){
- try {
- SocketAddress socketAddr1 = new InetSocketAddress(ip,port);
- socket = new Socket();
- socket.connect(socketAddr1);
- }
- catch (Exception ex) {
- System.out.println ("Do not Connect the TcpServer!/n"+ex);
- }
- }
- public static void sendThread(byte[] sendByte){
- int unitNo = 0;
- try{
- for(int k=0;k<5;k++)
- {
- bufos = new BufferedOutputStream(socket.getOutputStream());
- Thread.sleep(2000);
- bufos.write(sendByte);
- System.out.println ("k:"+k);
- bufos.flush();
- //bufos.close();
- }
- //开始时间戳,4个字节
- if(isException){
- isException = false;
- }
- }catch(Exception e){
- System.out.println(e);
- if(!isException){
- isException = true;
- }
- System.out.print("RealSend The program can't send the date!/n");
- //设定保存的目录
- }
- System.out.print("/n");
- }
- public static void main(String [] arsg){
- TcpClient tcpClient = new TcpClient();
- getTcpSocket();
- byte[] pp = new byte[4];
- ByteOperator.putStr(pp,0,4,"abcd");
- sendThread(pp);
- socketClose();
- }
- }
-
- package coldwind..socket.tools;
- public class ByteOperator{
- public ByteOperator(){
- }
- /**
- * 长整形转化为byte类型
- */
- public static void putLong(byte[] buf,int offset,long value) {
- buf[offset + 0] = (byte) ((value >> 56) & 0xff);
- buf[offset + 1] = (byte) ((value >> 48) & 0xff);
- buf[offset + 2] = (byte) ((value >> 40) & 0xff);
- buf[offset + 3] = (byte) ((value >> 32) & 0xff);
- buf[offset + 4] = (byte) ((value >> 24) & 0xff);
- buf[offset + 5] = (byte) ((value >> 16) & 0xff);
- buf[offset + 6] = (byte) ((value >> 8) & 0xff);
- buf[offset + 7] = (byte) ((value >> 0) & 0xff);
- }
- /**
- * 长整形转化为byte类型
- */
- public static void putReverseBytesLong(byte[] buf, int offset, long value) {
- buf[offset + 7] = (byte) (value >> 56);
- buf[offset + 6] = (byte) (value >> 48);
- buf[offset + 5] = (byte) (value >> 40);
- buf[offset + 4] = (byte) (value >> 32);
- buf[offset + 3] = (byte) (value >> 24);
- buf[offset + 2] = (byte) (value >> 16);
- buf[offset + 1] = (byte) (value >> 8);
- buf[offset + 0] = (byte) (value >> 0);
- }
- /**
- * byte 型转化为 Long 类型
- */
- public static long getLong(byte[] bytes, int index) {
- return ((((long) bytes[index + 0] & 0xff) << 56)
- | (((long) bytes[index + 1] & 0xff) << 48)
- | (((long) bytes[index + 2] & 0xff) << 40)
- | (((long) bytes[index + 3] & 0xff) << 32)
- | (((long) bytes[index + 4] & 0xff) << 24)
- | (((long) bytes[index + 5] & 0xff) << 16)
- | (((long) bytes[index + 6] & 0xff) << 8) | (((long) bytes[index + 7] & 0xff) << 0));
- }
- /**
- * byte 型转换为 Long 类型 高低位
- */
- public static long getReverseBytesLong(byte[] bytes, int index) {
- return ((((long) bytes[index + 7] & 0xff) << 56)
- | (((long) bytes[index + 6] & 0xff) << 48)
- | (((long) bytes[index + 5] & 0xff) << 40)
- | (((long) bytes[index + 4] & 0xff) << 32)
- | (((long) bytes[index + 3] & 0xff) << 24)
- | (((long) bytes[index + 2] & 0xff) << 16)
- | (((long) bytes[index + 1] & 0xff) << 8) | (((long) bytes[index + 0] & 0xff) << 0));
- }
- /**
- * 整形转化为byte类型
- */
- public static void putInt(byte[] buf,int offset,int value) {
- buf[offset+0] = (byte)((value >> 24) & 0xff);
- buf[offset+1] = (byte)((value >> 16) & 0xff);
- buf[offset+2] = (byte)((value >> 8) & 0xff);
- buf[offset+3] = (byte)((value >> 0) & 0xff);
- }
- /**
- * 整型转化为byte类型 高低位
- */
- public static void putReverseBytesInt(byte[] buf,int offset,int value) {
- buf[offset + 3] = (byte) (value >> 24);
- buf[offset + 2] = (byte) (value >> 16);
- buf[offset + 1] = (byte) (value >> 8);
- buf[offset + 0] = (byte) (value >> 0);
- }
- /**
- * 整形转化为byte类型
- */
- public static void putInt(byte[] buf,int offset,long value) {
- buf[offset+0] = (byte)((value >> 24) & 0xff);
- buf[offset+1] = (byte)((value >> 16) & 0xff);
- buf[offset+2] = (byte)((value >> 8) & 0xff);
- buf[offset+3] = (byte)((value >> 0) & 0xff);
- }
- /**
- * 整型转化为byte类型 高低位
- */
- public static void putReverseBytesInt(byte[] buf,int offset,long value) {
- buf[offset + 3] = (byte) (value >> 24);
- buf[offset + 2] = (byte) (value >> 16);
- buf[offset + 1] = (byte) (value >> 8);
- buf[offset + 0] = (byte) (value >> 0);
- }
- /**
- * byte类型转换为int型
- */
- public static int getInt(byte[] bytes, int index) {
- return (int) ((((bytes[index + 0] & 0xff) << 24) | ((bytes[index + 1] & 0xff) << 16) | ((bytes[index + 2] & 0xff) << 8) | ((bytes[index + 3] & 0xff) << 0)));
- }
- /**
- * byte类型转换为int 型 高低位
- */
- public static int getReverseBytesInt(byte[] bytes, int index) {
- return (int) ((((bytes[index + 3] & 0xff) << 24)
- | ((bytes[index + 2] & 0xff) << 16)
- | ((bytes[index + 1] & 0xff) << 8) | ((bytes[index + 0] & 0xff) << 0)));
- }
- /**
- * 浮点型转化为byte类型
- */
- public static void putFloat(byte[] buf,int offset,float value){
- try {
- putInt(buf,offset,Float.floatToIntBits(value));
- }
- catch (Exception ex) {
- System.out.print("convert the float to Byte is error!/n"+ex);
- }
- }
- /**
- * 浮点型转化为 byte类型 高低位
- */
- public static void putReverseBytesFloat(byte[] buf,int offset,float value) {
- try {
- putReverseBytesInt(buf,offset,Float.floatToIntBits(value));
- }
- catch (Exception ex) {
- System.out.print("convert the ReverseBytesFloat to Byte is error!/n");
- }
- }
- /**
- * byte类型转换为浮点型
- */
- public static float getReverseBytesFloat(byte[] bytes,int index){
- int num = ((bytes[index+3]<<24)0xFF000000)|((bytes[index+2]<<16)0xFF0000)|((bytes[index+1]<<8)0xFF00)|(bytes[index]0xFF);
- float f = Float.intBitsToFloat(num);
- return f;
- }
- /**
- * byte类型转换为 浮点型 高低位
- */
- public static float getFloat (byte[] bytes, int index) {
- int num = ((bytes[index]<<24)0xFF000000)|((bytes[index+1]<<16)0xFF0000)|((bytes[index+2]<<8)0xFF00)|(bytes[index+3]0xFF);
- float f = Float.intBitsToFloat(num);
- return f;
- }
- /**
- * 短整形转化为byte类型
- */
- public static void putShort(byte[] buf,int offset,short value) {
- buf[offset+0] = (byte)((value >> 8) & 0xff);
- buf[offset+1] = (byte)((value >> 0) & 0xff);
- }
- /**
- * short 转化为 byte 类型 高低对调
- */
- public static void putReverseBytesShort(byte[] buf,int offset,short value) {
- buf[offset] = (byte) (value >> 0);
- buf[offset + 1] = (byte) (value >> 8);
- }
- /**
- * byte 类型转换为 short型
- */
- public static short getShort(byte[] bytes, int index) {
- return (short) (((bytes[index] << 8) | bytes[index + 1] & 0xff));
- }
- /**
- * byte 类型转换为 short型 高低位
- */
- public static short getReverseBytesShort(byte[] bytes, int index) {
- return (short) (((bytes[index + 1] << 8) | bytes[index] & 0xff));
- }
- /**
- * byte型转换为char类型
- */
- public static char getChar(byte[] bytes,int index){
- return (char)(((bytes[index+1]<<8) | bytes[index] & 0xff));
- }
- /**
- * 字符串转化为byte类型
- */
- public static void putStr(byte[] buf,int offset,int length,String value) {
- try{
- byte[] tmpByte = value.getBytes();
- for(int i=length-1;i>=0;i--){
- // buf[offset+i] = tmpByte[i];
- buf[offset+i] = tmpByte[i];
- }
- }catch(Exception e)
- {
- System.out.print("convert the String to Byte is error!/n"+e);
- }
- }
- /**
- * byte型转换为字符串型
- */
- public static String getStr(byte[] bytes,int index,int length){
- byte[] str = new byte[length];
- for(int i=0;i<length;i++){
- str[i] = bytes[index+i];
- }
- return new String(str);
- }
- }
- 以上为vc和java写的tcp的服务器端和客户端,是那种一次连接多次发送的测试例子。本人水平有限,辛苦了好久才写成功,为写应用程序做测试。
本文提供了一个使用VC++和Java实现的TCP客户端-服务器通信示例,演示了一次连接后持续发送数据的过程。VC++部分使用Winsock库进行网络编程,而Java部分则利用标准库完成网络交互。
1024

被折叠的 条评论
为什么被折叠?



