- 论坛徽章:
- 0
|
我用C写的SERVER如下
#include <stdio.h>;
#include <sys/types.h>;
#include <sys/socket.h>;
#include <netinet/in.h>;
void process(int fd)
{
char buff[1000];
int received;
int help,read_bytes;
received = 100;
memset( buff,'.',received );
read_bytes = read(fd,buff,received);
if (read_bytes < 0) {
perror("read" ;
exit(1);
}
printf("%d bytes have received on socket %d\n",read_bytes,fd);
printf("buff=\n%s\n",buff);
for(help=0;help<received;help++)
if(buff[help] != '0'+help%10) {
printf("Error on position %d\n",help);
break;
}
}
int main(void)
{
int sockfd,newsockfd;
struct sockaddr_in myaddr,peer;
int addrlen1,addrlen2;
if ((sockfd = socket(AF_INET,SOCK_STREAM,0)) < 0 ) {
perror("socket" ;
exit(1);
}
addrlen1 = sizeof(myaddr);
myaddr.sin_family = AF_INET;
myaddr.sin_port = htons(10000);
myaddr.sin_addr.s_addr = INADDR_ANY;
if (bind(sockfd, (struct sockaddr *)&myaddr ,addrlen1) < 0 ) {
perror("bind" ;
exit(1);
}
if (listen(sockfd,5)) {
perror("listen" ;
exit(1);
}
for (;
{
addrlen2 = sizeof(peer);
newsockfd = accept(sockfd,(struct sockaddr *)&peer,&addrlen2);
if ( newsockfd < 0) {
perror("accept" ;
exit(1);
}
if (fork() == 0) {
close(sockfd);
printf("connection on socket %d from %s\n", newsockfd,
inet_ntoa(peer.sin_addr.s_addr));
process(newsockfd);
close(newsockfd);
exit(0);
}
close(newsockfd);
}
}
用JAVA 写的客户端如下
import java.io.*;
import java.net.*;
public class ctcp {
public static void main(String args[]) {
try{
if (args.length != 1){
System.out.println("USAGE: java Client servername" ;
return;
}
String connectto= args[0];
Socket connection;
// 连接服务器
if(connectto.equals("localhost" ){
connection=new Socket(InetAddress.getLocalHost(),10000);
}
else{
connection=new Socket(InetAddress.getByName(connectto),10000);
}
PrintWriter os=new PrintWriter(connection.getOutputStream());
char [] buff=new char[100];
int help;
for(help=0; help<100; help++) {
buff[help] = '9';
}
os.print(buff);
os.flush();
System.out.println(buff);
connection.close();//结束连接
}
catch(SecurityException e){
System.out.println("SecurityException when connecting Server!" ;
}
catch(IOException e){
System.out.println("IOException when connecting Server!" ;
}
}
}
客户端运行
E:\>;java ctcp 182.16.10.75
99999999999999999999999999999999999999999999999999999999999999999999999999999999
99999999999999999999
SERVER端却显示
connection on socket 4 from 182.16.10.15
100 bytes have received on socket 4
buff=
99999999999999999999999999999999999999999999999999999999999999999999999999999999
99999999999999999999
Error on position 0
我用C写的客户端程序正常,不明白为什么出错,请赐教 |
|