前段时间做一个项目,需要从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

点击(此处)折叠或打开

//service.c

/****************** server program *****************/

#include

#include

#include

#include

#include

#include

#include

#include

#include

#include

#include

#include

#include

#include //for unix domain socket

#include

int sockfd,newfd;

void *read_socket();

int main()

{

int ret;

int recv_num,recv_num_total=0;

char recv_buf[50];

pthread_t read_tid,write_tid;

struct sockaddr_in server_addr;

server_addr.sin_family=AF_INET;/*设置域为IPV4*/

server_addr.sin_addr.s_addr=INADDR_ANY;/*绑定到 INADDR_ANY 地址*/

server_addr.sin_port=htons(3333);/*通信端口号为3333,注意这里必须要用htons函数处理一下,不能直接写3333,否则可能会连不上*/

sockfd=socket(AF_INET,SOCK_STREAM,0);

if (sockfd<0)

{

printf("调用socket函数建立socket描述符出错!\n");

exit(1);

}

printf("调用socket函数建立socket描述符成功!\n");

ret=bind(sockfd,(struct sockaddr *)(&server_addr),sizeof(server_addr));

perror("server");

if (ret<0)

{

printf("调用bind函数绑定套接字与地址出错!\n");

exit(2);

}

printf("调用bind函数绑定套接字与地址成功!\n");

ret=listen(sockfd,4);

if (ret<0)

{

printf("调用listen函数出错,无法宣告服务器已经可以接受连接!\n");

exit(3);

}

printf("调用listen函数成功,宣告服务器已经可以接受连接请求!\n");

newfd=accept(sockfd,NULL,NULL);/*newfd连接到调用connect的客户端*/

if (newfd<0)

{

printf("调用accept函数出错,无法接受连接请求,建立连接失败!\n");

exit(4);

}

printf("调用accept函数成功,服务器与客户端建立连接成功!\n");

while (1)

{

memset(recv_buf,0,sizeof(recv_buf));/*清空一下recv_buf缓存区*/

recv_num=recv(newfd,recv_buf,26,0);

if (recv_num<0)

printf("服务器端:调用recv接收失败!\n");

else if(recv_num>0)

{

recv_num_total+=recv_num;

printf("服务器端:调用recv接收成功!本次接收到%d个字节,内容为:\"%s\"。共收到%d个字节的数据。\n",recv_num,recv_buf,recv_num_total);

sync();

}

else/*收到数据为0,表明服务器与客户端的连接已经中断*/

{

printf("服务器端:与客户端的连接已中断,当前共收到%d个字节的数据。服务器将再次等待客户端的连接。\n",recv_num_total);

newfd=accept(sockfd,NULL,NULL);/*当客户端退出后,再次开始接收客户端的连接*/

}

sleep(1);

}

}

c的客户端程序:client.c

点击(此处)折叠或打开

//client.c

#include

#include /* basic system data types */

#include /* basic socket definitions */

#include /* sockaddr_in{} and other Internet defns */

#include /* inet(3) functions */

#include /*gethostbyname function */

#include

#include

#include

#include

#define MAXLINE 10

#define HEAD_ARRAY_SIZE 28

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'};

void handle(int connfd);

int main(int argc, char **argv)

{

char * servInetAddr = "127.0.0.1";

int servPort = 3333;

char buf[MAXLINE];

int connfd;

struct sockaddr_in servaddr;

connfd = socket(AF_INET, SOCK_STREAM, 0);

bzero(&servaddr, sizeof(servaddr));

servaddr.sin_family = AF_INET;

servaddr.sin_port = htons(servPort);

inet_pton(AF_INET, servInetAddr, &servaddr.sin_addr);

if (connect(connfd, (struct sockaddr *) &servaddr, sizeof(servaddr)) < 0) {

perror("connect error");

return -1;

}

printf("welcome to echoclient\n");

handle(connfd); /* do it all */

close(connfd);

printf("exit\n");

exit(0);

}

void handle(int sockfd)

{

char sendline[MAXLINE], recvline[MAXLINE];

int n;

int i;

//for (i=0;i<10;i++)

for (;;)

{

if (fgets(sendline, MAXLINE, stdin) == NULL) {

break;//read eof

}

n = write(sockfd, sendline, strlen(sendline));

printf("write:%d\n",n);

/*

n = read(sockfd, recvline, MAXLINE);

if (n == 0) {

printf("echoclient: server terminated prematurely\n");

break;

}

write(STDOUT_FILENO, recvline, n);

*/

}

}

java的服务端程序:Server.java

点击(此处)折叠或打开

//Server.java

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

import java.io.PrintWriter;

import java.net.ServerSocket;

import java.net.Socket;

import java.util.concurrent.ExecutorService;

import java.util.concurrent.Executors;

public class Server {

private ServerSocket serverSocket;

private Socket socket;

private int port = 3333;

private ExecutorService executeService = Executors.newFixedThreadPool(10);

public Server(){

try {

serverSocket = new ServerSocket(port);

// serverSocket = new ServerSocket(port, 10, InetAddress.getByName("192.168.1.102"));

System.out.println("Server have been started.[" + serverSocket + "]");

while(true){

socket = serverSocket.accept();

executeService.submit(new Runnable(){

public void run(){

BufferedReader in = null;

PrintWriter out = null;

try{

in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

out = new PrintWriter(socket.getOutputStream(), true);

while (true) {

String line = in.readLine();

System.out.println("Server Received:[" + line + "]");

out.println("Server Received:[" + line + "]");

}

//out.close();

//in.close();

}catch (Exception e) {

e.printStackTrace();

}finally{

try {

out.close();

in.close();

socket.close();

} catch (IOException e) {

System.out.println("close socket error.");

e.printStackTrace();

}

}

}

});

}

} catch (Exception e) {

e.printStackTrace();

}finally{

try {

if(null != serverSocket){

serverSocket.close();

System.out.println("serverSocket close");

}

} catch (Exception e) {

e.printStackTrace();

}

}

}

public static void main(String[] args){

new Server();

}

}

java的客户端程序:Client.java

点击(此处)折叠或打开

//Client.java

/****************** Client program *****************/

import java.net.*;

import java.io.*;

public class Client {

static Socket server;

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

server = new Socket(InetAddress.getLocalHost(), 3333);

BufferedReader in = new BufferedReader(new InputStreamReader(server.getInputStream()));

PrintWriter out = new PrintWriter(server.getOutputStream());

BufferedReader wt = new BufferedReader(new InputStreamReader(System.in));

while (true) {

String str = wt.readLine();

out.println(str);

out.flush();

if (str.equals("end")) {

break;

}

//System.out.println("Back message from server:[" + in.readLine() + "]");

}

server.close();

}

}

编译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$