Chinaunix首页 | 论坛 | 博客
  • 博客访问: 97741
  • 博文数量: 24
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 171
  • 用 户 组: 普通用户
  • 注册时间: 2014-10-24 12:12
个人简介

好好学习天天向上

文章分类

全部博文(24)

文章存档

2018年(1)

2016年(7)

2015年(6)

2014年(10)

我的朋友

分类: LINUX

2016-02-17 17:09:21

前段时间做一个项目,需要从c语言的进程往java语言的进程发送数据,使用socket进行通信。于是在网上研究了一下java语言和c语言之间的socket通信,摘抄了一部分代码,实现了c的服务端和c的客户端通信,c的服务端和java的客户端通信,java的服务端和java的客户端通信,java的服务端和c的客户端通信。主要文件为如下四个:
c的服务端程序:service.c
c的客户端程序:client.c
java的服务端程序:Server.java
java的客户端程序:Client.java
下面分别贴出这四个程序,并贴出实际编译测试输出内容。

c的服务端程序:service.c

点击(此处)折叠或打开

  1. //service.c
  2. /****************** server program *****************/
  3. #include <unistd.h>
  4. #include <stdio.h>
  5. #include <stdlib.h>
  6. #include <string.h>
  7. #include <assert.h>
  8. #include <sys/types.h>
  9. #include <fcntl.h>
  10. #include <stdarg.h>
  11. #include <errno.h>
  12. #include <signal.h>
  13. #include <arpa/inet.h>
  14. #include <netdb.h>
  15. #include <sys/socket.h>
  16. #include <sys/un.h> //for unix domain socket
  17. #include <pthread.h>

  18. int sockfd,newfd;
  19. void *read_socket();

  20. int main()
  21. {
  22.     int ret;
  23.     
  24.     int recv_num,recv_num_total=0;
  25.     char recv_buf[50];
  26.     
  27.     
  28.     pthread_t read_tid,write_tid;
  29.     struct sockaddr_in server_addr;
  30.     server_addr.sin_family=AF_INET;/*设置域为IPV4*/
  31.     server_addr.sin_addr.s_addr=INADDR_ANY;/*绑定到 INADDR_ANY 地址*/
  32.     server_addr.sin_port=htons(3333);/*通信端口号为3333,注意这里必须要用htons函数处理一下,不能直接写3333,否则可能会连不上*/
  33.     sockfd=socket(AF_INET,SOCK_STREAM,0);
  34.     if (sockfd<0)
  35.     {
  36.         printf("调用socket函数建立socket描述符出错!\n");
  37.          exit(1);
  38.     }
  39.     printf("调用socket函数建立socket描述符成功!\n");
  40.     ret=bind(sockfd,(struct sockaddr *)(&server_addr),sizeof(server_addr));
  41.     perror("server");
  42.     if (ret<0)
  43.     {
  44.         printf("调用bind函数绑定套接字与地址出错!\n");
  45.          exit(2);
  46.     }
  47.     printf("调用bind函数绑定套接字与地址成功!\n");
  48.     ret=listen(sockfd,4);
  49.     if (ret<0)
  50.     {
  51.         printf("调用listen函数出错,无法宣告服务器已经可以接受连接!\n");
  52.          exit(3);
  53.     }
  54.     printf("调用listen函数成功,宣告服务器已经可以接受连接请求!\n");
  55.     newfd=accept(sockfd,NULL,NULL);/*newfd连接到调用connect的客户端*/
  56.     if (newfd<0)
  57.     {
  58.         printf("调用accept函数出错,无法接受连接请求,建立连接失败!\n");
  59.          exit(4);
  60.     }
  61.     printf("调用accept函数成功,服务器与客户端建立连接成功!\n");
  62.    
  63.     while (1)
  64.     {
  65.         memset(recv_buf,0,sizeof(recv_buf));/*清空一下recv_buf缓存区*/
  66.         recv_num=recv(newfd,recv_buf,26,0);
  67.         if (recv_num<0)
  68.             printf("服务器端:调用recv接收失败!\n");
  69.         else if(recv_num>0)
  70.         {
  71.             recv_num_total+=recv_num;
  72.             printf("服务器端:调用recv接收成功!本次接收到%d个字节,内容为:\"%s\"。共收到%d个字节的数据。\n",recv_num,recv_buf,recv_num_total);
  73.             sync();
  74.         }
  75.         else/*收到数据为0,表明服务器与客户端的连接已经中断*/
  76.         {
  77.             printf("服务器端:与客户端的连接已中断,当前共收到%d个字节的数据。服务器将再次等待客户端的连接。\n",recv_num_total);
  78.             newfd=accept(sockfd,NULL,NULL);/*当客户端退出后,再次开始接收客户端的连接*/
  79.         }
  80.         sleep(1);
  81.     }
  82.    
  83. }
c的客户端程序:client.c

点击(此处)折叠或打开

  1. //client.c
  2. #include <unistd.h>
  3. #include <sys/types.h> /* basic system data types */
  4. #include <sys/socket.h> /* basic socket definitions */
  5. #include <netinet/in.h> /* sockaddr_in{} and other Internet defns */
  6. #include <arpa/inet.h> /* inet(3) functions */
  7. #include <netdb.h> /*gethostbyname function */

  8. #include <stdlib.h>
  9. #include <errno.h>
  10. #include <stdio.h>
  11. #include <string.h>

  12. #define MAXLINE 10
  13. #define HEAD_ARRAY_SIZE 28
  14. static char head_array[HEAD_ARRAY_SIZE]={'&','d','a','t','a','=','1','|','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','1','1','|','\r'};



  15. void handle(int connfd);

  16. int main(int argc, char **argv)
  17. {
  18.     char * servInetAddr = "127.0.0.1";
  19.     int servPort = 3333;
  20.     char buf[MAXLINE];
  21.     int connfd;
  22.     struct sockaddr_in servaddr;

  23.     connfd = socket(AF_INET, SOCK_STREAM, 0);

  24.     bzero(&servaddr, sizeof(servaddr));
  25.     servaddr.sin_family = AF_INET;
  26.     servaddr.sin_port = htons(servPort);
  27.     inet_pton(AF_INET, servInetAddr, &servaddr.sin_addr);

  28.     if (connect(connfd, (struct sockaddr *) &servaddr, sizeof(servaddr)) < 0) {
  29.         perror("connect error");
  30.         return -1;
  31.     }
  32.     printf("welcome to echoclient\n");
  33.     handle(connfd); /* do it all */
  34.     close(connfd);
  35.     printf("exit\n");
  36.     exit(0);
  37. }

  38. void handle(int sockfd)
  39. {
  40.     char sendline[MAXLINE], recvline[MAXLINE];
  41.     int n;
  42.     int i;
  43.     //for (i=0;i<10;i++)
  44.     for (;;)        
  45.     {

  46.         if (fgets(sendline, MAXLINE, stdin) == NULL) {
  47.             break;//read eof
  48.         }
  49.         
  50.         n = write(sockfd, sendline, strlen(sendline));
  51.         printf("write:%d\n",n);
  52.         /*
            n = read(sockfd, recvline, MAXLINE);
            if (n == 0) {
                printf("echoclient: server terminated prematurely\n");
                break;
            }
            write(STDOUT_FILENO, recvline, n);
            */

  53.     }
  54. }

java的服务端程序:Server.java

点击(此处)折叠或打开

  1. //Server.java
  2.       
  3. import java.io.BufferedReader;
  4. import java.io.IOException;
  5. import java.io.InputStreamReader;
  6. import java.io.PrintWriter;
  7. import java.net.ServerSocket;
  8. import java.net.Socket;
  9. import java.util.concurrent.ExecutorService;
  10. import java.util.concurrent.Executors;
  11.       
  12. public class Server {
  13.     private ServerSocket serverSocket;
  14.     private Socket socket;
  15.     private int port = 3333;
  16.     private ExecutorService executeService = Executors.newFixedThreadPool(10);
  17.     
  18.     public Server(){
  19.         try {
  20.             serverSocket = new ServerSocket(port);
  21. // serverSocket = new ServerSocket(port, 10, InetAddress.getByName("192.168.1.102"));
  22.             System.out.println("Server have been started.[" + serverSocket + "]");
  23.             while(true){
  24.                     socket = serverSocket.accept();
  25.                     executeService.submit(new Runnable(){
  26.                         public void run(){
  27.                         BufferedReader in = null;
  28.                         PrintWriter out = null;    
  29.                             try{
  30.                                 in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
  31.                                 out = new PrintWriter(socket.getOutputStream(), true);
  32.                                 while (true) {
  33.                                     String line = in.readLine();
  34.                                     System.out.println("Server Received:[" + line + "]");                                 
  35.                                     out.println("Server Received:[" + line + "]");
  36.                                 }
  37.                                 //out.close();
  38.                                 //in.close();
  39.                             }catch (Exception e) {
  40.                                 e.printStackTrace();
  41.                             }finally{
  42.                                 try {
  43.                                     out.close();
  44.                                     in.close();
  45.                                     socket.close();
  46.                                 } catch (IOException e) {
  47.                                     System.out.println("close socket error.");
  48.                                     e.printStackTrace();
  49.                                 }
  50.                             }
  51.                         }
  52.                     });
  53.             }
  54.         } catch (Exception e) {
  55.             e.printStackTrace();
  56.         }finally{
  57.             try {
  58.                 if(null != serverSocket){
  59.                     serverSocket.close();
  60.                     System.out.println("serverSocket close");
  61.                 }
  62.             } catch (Exception e) {
  63.                 e.printStackTrace();
  64.             }
  65.         }
  66.     }
  67.     public static void main(String[] args){
  68.         new Server();
  69.     }     
  70. }

java的客户端程序:Client.java

点击(此处)折叠或打开

  1. //Client.java
  2. /****************** Client program *****************/
  3. import java.net.*;
  4. import java.io.*;

  5. public class Client {
  6. static Socket server;

  7. public static void main(String[] args) throws Exception {
  8.    server = new Socket(InetAddress.getLocalHost(), 3333);
  9.    BufferedReader in = new BufferedReader(new InputStreamReader(server.getInputStream()));
  10.    PrintWriter out = new PrintWriter(server.getOutputStream());
  11.    BufferedReader wt = new BufferedReader(new InputStreamReader(System.in));

  12.    while (true) {
  13.     String str = wt.readLine();
  14.     out.println(str);
  15.     out.flush();
  16.     if (str.equals("end")) {
  17.      break;
  18.     }
  19.     //System.out.println("Back message from server:[" + in.readLine() + "]");
  20.    }
  21.    server.close();
  22. }
  23. }

编译c语言服务端和客户端:
chenyun@software9:~/workspace/socket$ gcc -o server service.c
chenyun@software9:~/workspace/socket$ gcc -o client client.c

编译java语言服务端和客户端:
chenyun@software9:~/workspace/socket$ javac Server.java
chenyun@software9:~/workspace/socket$ javac Client.java

打开一个终端,运行c语言服务端,另外再打开一个终端,先运行c语言客户端,输入12345回车,再输入123456789回车,以及abcdefghijklmnd回车,以及单独回车等内容,看服务端显示,此时服务端正确显示客户端发送内容。按ctrl+C按键,退出c语言客户端,此时,查看服务端显示,此时服务端显示连接断开,等待重新连接。重新选择运行java的客户端,仿照c客户端输入12345回车等内容,查看服务端显示,此时服务端重新被连接,并且正确显示客户端发送内容,按ctrl+C按键,退出java语言客户端。
c语言服务端的输出显示如下:
chenyun@software9:~/workspace/socket$
chenyun@software9:~/workspace/socket$ ./server
调用socket函数建立socket描述符成功!
server: Success
调用bind函数绑定套接字与地址成功!
调用listen函数成功,宣告服务器已经可以接受连接请求!
调用accept函数成功,服务器与客户端建立连接成功!
服务器端:调用recv接收成功!本次接收到6个字节,内容为:"12345
"。共收到6个字节的数据。
服务器端:调用recv接收成功!本次接收到10个字节,内容为:"123456789
"。共收到16个字节的数据。
服务器端:调用recv接收成功!本次接收到1个字节,内容为:"
"。共收到17个字节的数据。
服务器端:调用recv接收成功!本次接收到1个字节,内容为:"
"。共收到18个字节的数据。
服务器端:调用recv接收成功!本次接收到15个字节,内容为:"abcdefghijklmn
"。共收到33个字节的数据。
服务器端:与客户端的连接已中断,当前共收到33个字节的数据。服务器将再次等待客户端的连接。
服务器端:调用recv接收成功!本次接收到6个字节,内容为:"12345
"。共收到39个字节的数据。
服务器端:调用recv接收成功!本次接收到10个字节,内容为:"123456789
"。共收到49个字节的数据。
服务器端:调用recv接收成功!本次接收到15个字节,内容为:"abcdefghijklmn
"。共收到64个字节的数据。
服务器端:调用recv接收成功!本次接收到1个字节,内容为:"
"。共收到65个字节的数据。
服务器端:调用recv接收成功!本次接收到1个字节,内容为:"
"。共收到66个字节的数据。
服务器端:调用recv接收成功!本次接收到4个字节,内容为:"abc
"。共收到70个字节的数据。
服务器端:与客户端的连接已中断,当前共收到70个字节的数据。服务器将再次等待客户端的连接。
^C
chenyun@software9:~/workspace/socket$

c及java语言客户端显示如下:
chenyun@software9:~/workspace/socket$
chenyun@software9:~/workspace/socket$ ./client
welcome to echoclient
12345
write:6
123456789
write:9
write:1
(此处回车)
write:1
(此处回车)
write:1
abcdefghijklmn
write:9
write:6
^C            
chenyun@software9:~/workspace/socket$
chenyun@software9:~/workspace/socket$
chenyun@software9:~/workspace/socket$ java Client
12345
123456789
abcdefghijklmn
(此处回车)
(此处回车)
abc
^Cchenyun@software9:~/workspace/socket$
chenyun@software9:~/workspace/socket$

下面的过程和上面是类似的,就是用java做服务器,用java和c分别连接。
打开一个终端,运行java语言服务端,另外再打开一个终端,先运行java语言客户端,输入12345回车,再输入123456789回车,以及 abcdefghijklmnd回车,以及单独回车等内容,看服务端显示,此时服务端正确显示客户端发送内容。按ctrl+C按键,退出java语言客户端,此时,查看服务端显示,此时服务端显示连接断开,等待重新连接。重新选择运行c的客户端,仿照java客户端输入12345回车等内容,查看服务端显示,此时服务端重新被连接,并且正确显示客户端发送内容,按ctrl+C按键,退出c语言客户端。
java语言服务端的输出显示如下:
chenyun@software9:~/workspace/socket$ java Server
Server have been started.[ServerSocket[addr=0.0.0.0/0.0.0.0,localport=3333]]
Server Received:[12345]
Server Received:[123456789]
Server Received:[]
Server Received:[]
Server Received:[abcdefghijklmn]
java.net.SocketException: Connection reset
    at java.net.SocketInputStream.read(SocketInputStream.java:196)
    at java.net.SocketInputStream.read(SocketInputStream.java:122)
    at sun.nio.cs.StreamDecoder.readBytes(StreamDecoder.java:283)
    at sun.nio.cs.StreamDecoder.implRead(StreamDecoder.java:325)
    at sun.nio.cs.StreamDecoder.read(StreamDecoder.java:177)
    at java.io.InputStreamReader.read(InputStreamReader.java:184)
    at java.io.BufferedReader.fill(BufferedReader.java:154)
    at java.io.BufferedReader.readLine(BufferedReader.java:317)
    at java.io.BufferedReader.readLine(BufferedReader.java:382)
    at Server$1.run(Server.java:33)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471)
    at java.util.concurrent.FutureTask.run(FutureTask.java:262)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:745)
Server Received:[12345]
Server Received:[123456789]
Server Received:[]
Server Received:[]
Server Received:[abcdefghijklmn]
java.net.SocketException: Connection reset
    at java.net.SocketInputStream.read(SocketInputStream.java:196)
    at java.net.SocketInputStream.read(SocketInputStream.java:122)
    at sun.nio.cs.StreamDecoder.readBytes(StreamDecoder.java:283)
    at sun.nio.cs.StreamDecoder.implRead(StreamDecoder.java:325)
    at sun.nio.cs.StreamDecoder.read(StreamDecoder.java:177)
    at java.io.InputStreamReader.read(InputStreamReader.java:184)
    at java.io.BufferedReader.fill(BufferedReader.java:154)
    at java.io.BufferedReader.readLine(BufferedReader.java:317)
    at java.io.BufferedReader.readLine(BufferedReader.java:382)
    at Server$1.run(Server.java:33)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471)
    at java.util.concurrent.FutureTask.run(FutureTask.java:262)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:745)
^Cchenyun@software9:~/workspace/socket$
chenyun@software9:~/workspace/socket$
chenyun@software9:~/workspace/socket$
chenyun@software9:~/workspace/socket$

java及c的客户端显示内容如下:
chenyun@software9:~/workspace/socket$
chenyun@software9:~/workspace/socket$ java Client
12345
123456789
(此处回车)
(此处回车)
abcdefghijklmn
^Cchenyun@software9:~/workspace/socket$
chenyun@software9:~/workspace/socket$
chenyun@software9:~/workspace/socket$
chenyun@software9:~/workspace/socket$
chenyun@software9:~/workspace/socket$ ./client
welcome to echoclient
12345
write:6
123456789
write:9
write:1

write:1

write:1
abcdefghijklmn
write:9
write:6
^C
chenyun@software9:~/workspace/socket$







阅读(2706) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~