全部博文(116)
分类:
2005-11-17 22:24:41
出于工作的需要,今天写了一个服务程序,后来为了测试,还写了个客户端的程序.反正原理很简单,并且以后还可以套用.所以在这里存档.
server
-----------------------------------------------------
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#define SERV_PORT 9970
#define LISTENQ 10
#define MAXDATASIZE 204800
int main(int argc, char **argv)
{
int listenfd,client_fd;
size_t sin_size;
struct sockaddr_in server_addr,client_addr;
signal(SIGCHLD,SIG_IGN);
if( (listenfd = socket(AF_INET,SOCK_STREAM,0)) == -1)
{
perror("socket create error!");
exit(1);
}
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
server_addr.sin_port = htons(SERV_PORT);
bzero(&(server_addr.sin_zero),8);
if( bind(listenfd,(struct sockaddr *)&server_addr,sizeof(server_addr)) == -1)
{
perror("bind error!");
exit(1);
}
if(listen(listenfd,LISTENQ) == -1)
{
perror("listen error!");
exit(1);
}
while(1)
{
sin_size = sizeof(struct sockaddr_in );
if (( client_fd = accept(listenfd, (struct sockaddr *)&client_addr, &sin_size)) == -1)
{
perror("accpt error");
continue;
}
if (!fork())
{
char getBuf[MAXDATASIZE];
char *revBuf;
int recvbytes;
memset(getBuf, 0, sizeof(getBuf));
if ((recvbytes=recv(client_fd, getBuf, MAXDATASIZE, 0)) ==-1)
{
perror("recv出错!");
exit(1);
}
getBuf[recvbytes] = ' ';
printf("Received: %s",getBuf);
revBuf=(char *)malloc(128);
sprintf(revBuf,"hello,world!
");
int sendbytes = send(client_fd, revBuf, strlen(revBuf), 0);
printf("sendbytes : %d
", sendbytes);
printf("revBuf : %s
", revBuf);
printf("close socket
");
shutdown(client_fd, 2);
close(client_fd);
exit(0);
}
}
}
client
-------------------------------------------
import java.io.*;
import java.net.*;
public class Client
{
public Client()
{
try
{
Socket socket = new Socket("127.0.0.1", 9970);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(),true);
BufferedReader line = new BufferedReader(new InputStreamReader(System.in));
out.println("12 CheckUser PF|00040001|");
System.out.println(in.readLine());
line.close();
out.close();
in.close();
socket.close();
}
catch (IOException e){}
}
public static void main(String[] args) {
new Client();
}
}
服务端在cgywin下编译通过,用c写的.
客户端用java写的,在windows xp下编译.
两个配合起来使用,天衣无缝.爽