四国研究所

伟大而光荣的四国研究所在大家的努力下向前走

52 成员544 主题2,815 回复0 张照片

给老大的......(文件一:ChatRoom.java)

大
大蒜头,四国研究所
2001-04-10 15:13
/*
* ChatRoom.java
*
* Created on 2001年1月15日, 下午7:31
*/
import java.io.*;
//import recieve.Reciever.*;
/**
*
* @author garlic
* @version
*/
public class ChatRoom {

public static void main(String args[]){
String select;//选择启动方式(服务器方式或客户方式)
String ip;//服务器的ip地址
//boolean done=false;

System.out.println("--------Welcome to use my Chatroom Programm------");
System.out.println("1.Server");
System.out.println("2.Client");
System.out.println("3.Quit");
System.out.print("Please enter your choice:(1-3)");

select=Console.readLine();

if (select.equals("1")){ //选择服务器方式
RunServer rS=new RunServer(); //创建一个服务器对象
rS.start();
}else if(select.equals("2")){//选择客户方式

ip=Console.readLine("Please input the Ipaddress of the server:");
//System.out.println(ip);
RunClient rC=new RunClient(ip);//创建一个客户对象
rC.start();
}else if(select.equals("3")){//退出程序
System.exit(0);
}else{
System.out.println("Invalid char inputed,Please retry(1-3)");
}


}

}
大
大蒜头,四国研究所
2001-04-10 23:14
文件二:RunClient.java
/*
* RunClient.java
*
* Created on 2001年1月15日, 下午7:31
*/
import java.io.*;
import java.net.*;
import java.util.*;

/**
*
* @author root
* @version
*/
public class RunClient {
Client client;//=new Client("127.0.0.1",8001);

String Ipaddress="127.0.0.1";//默认的服务器是本机
BufferedReader reader;
PrintWriter writer;
//constructor
public RunClient(String ip){
if (ip!=null&&!ip.equals("")){
Ipaddress=ip;
}
//System.out.print("IPaddress:"+Ipaddress);
}


public void start() {
//System.out.println("Ipaddress:"+"***"+Ipaddress);
client=new Client(Ipaddress,8001);
runCRecieve rCR=new runCRecieve(client);
Thread tCR=new Thread(rCR);

runCSend rCS=new runCSend(client);
Thread tCS=new Thread(rCS);

tCR.start();
tCS.start();

}

}

class runCRecieve implements Runnable{
String InputStr;
BufferedReader reader;
Client client;

public runCRecieve(Client client){
this.client=client;
}

public void run(){
//System.out.println("i can enter RUN");
try{
reader=new BufferedReader(new InputStreamReader(client.in));
while(true){
//System.out.println(IfExit);
InputStr=reader.readLine();
if (InputStr!=null&&!InputStr.equals("bye")){
System.out.println("SERVER>"+InputStr);

}else{
System.out.println("The Server has left the chatroom.");
System.exit(0);
//待编码处理
}
}
}catch(IOException e){
//异常原因不明,先作退出处理。
System.out.println("IOEx"+e);
System.out.println("the server has left the chatroom.");
System.exit(0);
}
}
}

class runCSend implements Runnable{
PrintWriter writer;
String OutputStr;
Client client;

public runCSend(Client client){
this.client=client;
}

public void run(){

writer=new PrintWriter(new OutputStreamWriter(client.out),true);
while(true){
OutputStr=Console.readLine();
if(OutputStr.equals("bye")){
System.exit(0);
}
writer.println(OutputStr);
}
}
}

class Client{
public InputStream in;
public OutputStream out;

private Socket cSocket;

public Client(String host,int port){
//System.out.println("host:"+host);
try{
cSocket=new Socket(host,port);
System.out.println("Client request connect to the server"+cSocket);

in=cSocket.getInputStream();
out=cSocket.getOutputStream();
}catch(IOException e){
System.out.println("IOExc :"+e);
}
}
}
大
大蒜头,四国研究所
2001-04-10 23:14
文件三:RunServer.java
*
* RunServer.java
*
* Created on 2001年1月16日, 上午10:45
*/
import java.util.*;
import java.io.*;
import java.net.*;

//import server.Server;
/**
*
* @author root
* @version
*/
public class RunServer{
Server server=new Server(8001);
//static boolean IfExit =false;
BufferedReader reader;
PrintWriter writer;

/** Creates new RunServer */
public void start(){
String InputStr;

runSRecieve rSR=new runSRecieve(server);
Thread tSR=new Thread(rSR);

runSSend rSS=new runSSend(server);
Thread tSS=new Thread(rSS);

tSR.start();
tSS.start();
//System.out.println("Exit now!");
}
}

class runSRecieve implements Runnable{
String InputStr;
BufferedReader reader;
Server server;

public runSRecieve(Server server){
this.server=server;
}

public void run(){

try{
reader=new BufferedReader(new InputStreamReader(server.in));
while(true){

InputStr=reader.readLine();

if (InputStr!=null&&!InputStr.equals("bye")){
System.out.println("CLIENT>"+InputStr);
}else{
System.out.println("The client has left the chatroom.");
System.exit(0);
//待编码处理
}

}
}catch(IOException e){
//异常原因不明,先作退出处理
System.out.println("IOEx"+e);
System.out.println("The client has left the chatroom.");
System.exit(0);
}
}
}

class runSSend implements Runnable{
PrintWriter writer;
String OutputStr;
Server server;

public runSSend(Server server){
this.server=server;
}

public void run(){
writer=new PrintWriter(new OutputStreamWriter(server.out),true);
while(true){
OutputStr=Console.readLine();
if(OutputStr.equals("bye")){
System.exit(0);
}
writer.println(OutputStr);
}
}
}

class Server{
private ServerSocket sSocket;
private Socket socket;

public InputStream in;
public OutputStream out;

/** Creates new Server */
public Server(int port) {

try{
sSocket=new ServerSocket(port);
System.out.println("Server is running now,waiting for connect...");

socket=sSocket.accept();
System.out.println("Sever after accept:"+sSocket);

in=socket.getInputStream();
out=socket.getOutputStream();
}catch (IOException e){
System.out.println("Server constructor IOEx: "+e);
}
}
}

大
大蒜头,四国研究所
2001-04-10 23:15
文件四:Console.java

public class Console
{ /**
print a prompt on the console but don't print a newline

@param prompt the prompt string to display
*/

public static void printPrompt(String prompt)
{ System.out.print(prompt + " ");
System.out.flush();
}

public static String readLine()
{ int ch;
String r = "";

boolean done = false;
while (!done)
{ try
{ ch = System.in.read();
if (ch < 0 || (char)ch == '\n')
done = true;
else if ((char)ch != '\r') // weird--it used to do \r\n translation
//System.out.print("ch=");
//System.out.println((char)ch);

r = r + (char) ch;
//System.out.print("r=");
//System.out.println(r);
}
catch(java.io.IOException e)
{ done = true;
}
}
return r;
}

public static String readLine(String prompt)
{ printPrompt(prompt);
return readLine();
}


}
叶
叶@四国研究所
2001-04-10 23:18
3ku
心迹所到之处一定比足迹所到更为遥远与辽阔......
..._/\_
.__ /__
<_ _>
..|/ )|
..../

四国研究所
大
大蒜头,四国研究所
2001-04-10 23:19
说明
偶这里不能发附件,所以只能把代码放到家里来了:)
谁懂java的帮偶捉捉bug,提点建议
偶也顺便捞点积分啦 :))
G
Guest
2001-04-11 00:41
叶子,侬的尾图有何含义?
偶比较本本,不大看得懂得,解释一下叭
叶
叶@四国研究所
2001-04-11 00:46
抽象呗:)
心迹所到之处一定比足迹所到更为遥远与辽阔......

四国研究所
黄
黄药师∈四国研究所
2001-04-11 03:15
呵呵
叶子那个图偶看了半天,发现好像是一个人的脸,闭着眼张着嘴干吗呢,:)
我已剪短我的发,剪一地卷毛,剩下一头漂亮的板刷;短短直直,整整齐齐,一寸一寸在自夸。:)
小
小菜@/dev/null
2001-04-11 03:37
好像有个问题,虽然RunServer可以同时接受多个incoming connection,但是好像只能和第一个连进来的client通话,不太象chat server.ibm developer网站的java栏目里面有个
做的比较全的java chat server,可以去cc:)
http://www6.software.ibm.com/developerworks/education/j-chat/


大
大蒜头,四国研究所
2001-04-11 04:37
呵呵,这个只是聊天室1.0版,是点对点的,不支持多方通信,没有用户界面,但是加入了多线程功能,是我在过年前搞的,然后就一直扔在那里没怎么动过。等有空了再作改进
多谢小菜的建议
叶
叶@四国研究所
2001-04-11 06:28
唉,其实是个符号组成的叶子,可是不知道怎么到了签名档里面就扭曲着这样了,偶也比较郁闷的,所以把它去掉了。
心迹所到之处一定比足迹所到更为遥远与辽阔......

四国研究所
大
大蒜头,四国研究所
2001-04-11 06:56
心中有叶即可,嘿嘿 ^_*
小
小菜@/dev/null
2001-04-11 10:48
眼前 也可有叶呀:)
,
}`-. , ,
\ \ '-' \ .-'{
_} . | ,`\ / ' ; .-;\
{ \ | | / `/ '-.,/ ; |
{ -- -. ' '`-, .--._.' ; \__
\ \ | ' / |`. ; _,`\
'. '- ' `_- '.`; ; ,-`_.-'
,--. \ ` /` '--' `;.` (` _
.--.\ '._) '-. \ \ `-. ; `-';|
'. -. ' __ '. ; ; _,-' /
{ __'.\ ' '-,/; `-' ';`.- ` .-'
'-. `-._' | `; ;`' .-'`
<_ -' ` .\ `; ; (_.'`\
_.;-"``"'-._'. `:; ___, _.-' |
.-''. '.` \ \_,_`\ ;##` `'; _.'
/_'._\ \ \__;#####./###. \`
\.' .'`/"`/ (#######)###::.. _.'
'.' .' ; , |:. `|()##`"""`
`'-../__/_\:: /O()()o
()'._.'`()()'
















小
小鱼儿〖四国研究所〗
2001-04-13 07:13
哇,这里还有编程啊?
呵呵,好久没用Java做程序了……
Java的Chatroom初始化较慢,所以很少用……
可惜我只会简单得使用Unix的OS命令来做聊天服务器和Client

Java本身支持Multi-tasking,做chatroom应该是擅长的

需要查一下Java是如何调用fork功能,那样可能可以实现duplex mode交流……(这方面目前没研究过)
我觉得问题可能是在Server是个单独的个体,要同时和多方交流,就必须给他一个synchronize的模式……如果JAva 也能调用类似于Unix 的系统fork命令,就可以生成很多Child(可以继承parent特性)来各自与对应的Client交流,当client退出,只要释放对应的socket就可以了……

我有一个用C写的server/client Unix 系统聊天程序,还支持简单的文件传送和LOG FILE记录,看看不知道是否有启发……

这里好像只用了Java操作thread的基本功能,可以试试synchronize命令吗(等我考完研究研究……实在已经有一年没用Java,都快忘了……嘻嘻……)
小
小鱼儿〖四国研究所〗
2001-04-13 07:15
哇,这里还有编程啊?
呵呵,好久没用Java做程序了……
Java的Chatroom初始化较慢,所以很少用……
可惜我只会简单得使用Unix的OS命令来做聊天服务器和Client

Java本身支持Multi-tasking,做chatroom应该是擅长的

需要查一下Java是如何调用fork功能,那样可能可以实现duplex mode交流……(这方面目前没研究过)
我觉得问题可能是在Server是个单独的个体,要同时和多方交流,就必须给他一个synchronize的模式……如果JAva 也能调用类似于Unix 的系统fork命令,就可以生成很多Child(可以继承parent特性)来各自与对应的Client交流,当client退出,只要释放对应的socket就可以了……

我有一个用C写的server/client Unix 系统聊天程序,还支持简单的文件传送和LOG FILE记录,看看不知道是否有启发……

这里好像只用了Java操作thread的基本功能,可以试试synchronize命令吗(等我考完研究研究……实在已经有一年没用Java,都快忘了……嘻嘻……)
小
小鱼儿〖四国研究所〗
2001-04-13 07:17
c7.c (>gcc -i c7.c client)
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/time.h>
#include <fcntl.h>

#define PORT 22222
static char buf[BUFSIZ];
static char cbuf[BUFSIZ];

void set_unblock(int sock)
{
if(fcntl(sock,F_SETFL,FNDELAY)<0)
{
perror("File control");
exit(2);
}
}


///////////////////////////////////////

//check user command
//-1 error command
//0 normal message
//1 clear screen
//2 send file
//3 get own id
int WhichCommand(char usercmd[])
{
char tbuf[201];
char tbuf1[101];
char tbuf2[101];
char tbuf3[101];
int i;

//convert to upper case
strncpy(tbuf,usercmd,200);
for (i=0; i<strlen(tbuf); i++) tbuf[i]=toupper(tbuf[i]);

//extract command

//CLEAR
if (strcmp(tbuf,"/CLEAR\n")==0) return 1;

//SEND, will check that there are 3 parameters and 2nd one is an integer
i=sscanf(tbuf,"%s %s %s",tbuf1,tbuf2,tbuf3);
if ((strcmp(tbuf1,"/SEND\n")==0) || (strcmp(tbuf1,"/SEND")==0))
{
//check there are 3 parameters
if (i!=3)
{
printf("Error : Incomplete command\n");
write(fileno(stdout),"> ",3);
fflush(stdout);
return -1;
}
//check 2nd parameter is integer
else
{
if (atoi(tbuf2)>0) return 2;
else
{
printf("Error : Invalid receiver\n");
write(fileno(stdout),"> ",3);
fflush(stdout);
return -1;
}
}
}

//OWNID
sscanf(tbuf,"%s",tbuf1);
if (strcmp(tbuf1,"/OWNID")==0) return 3;

return 0;
}

///////////////////////////////////////

//check if server sends error message
//error message in the form </error .... ...>
//return positive number if error is sent, negative if not sent
int ErrorMessage(char *msg)
{
char t1[100];
sscanf(msg,"%s",t1);
if (strcmp("/error",t1)==0) return 1;
else return -1;
}

///////////////////////////////////////

//check if server sends getdirectory command
//return 1 if server sends such a command, -1 if not
int GetDirectoryMessage(char *msg)
{
char t1[100];
sscanf(msg,"%s",t1);
if (strcmp("/getdirectory",t1)==0) return 1;
else return -1;
}

///////////////////////////////////////

//check if server sends copy files command
//return 1 if server sends such a command, -1 if not
int CopyFile(char *msg)
{
char t1[100];
sscanf(msg,"%s",t1);
if (strcmp("/copy",t1)==0) return 1;
else return -1;
}

///////////////////////////////////////

//clear screen
int ClearScreen()
{
int i;
for (i=1; i<=50; i++) write(fileno(stdout),"\n",1);
write(fileno(stdout),"> ",3);
return 0;
}

///////////////////////////////////////

main(int argc,char *argv[])
{
int orig_sock,len,n_ready;
static struct sockaddr_in serv_adr;
struct hostent *host;
struct timeval time_2_wait;
pid_t cpid;

char *argin[3];
int status;
int whichcmd;
char tch1[100],tch2[100],tch3[100];
int tint1,tint2;

fd_set read_fd;
time_2_wait.tv_sec = 1;

if(argc!=2)
{
fprintf(stderr,"usage");
exit(1);
}
host=gethostbyname(argv[1]);

if(host==(struct hostent *)NULL)
{
perror("gethostbyname");
exit(2);
}

memset(&serv_adr,0,sizeof(serv_adr));
serv_adr.sin_family=AF_INET;
memcpy(&serv_adr.sin_addr,host->h_addr,host->h_length);
serv_adr.sin_port=htons(PORT);

if((orig_sock=socket(AF_INET,SOCK_STREAM,0))<0)
{
perror("generate error");
exit(3);
}

if(connect(orig_sock,(struct orig_sockaddr *)&serv_adr,sizeof(serv_adr))<0)
{
perror("connect error");
exit(4);
}


set_unblock(fileno(stdin));
set_unblock(orig_sock);

write(fileno(stdout),"> ",2);

do
{
memset(&cbuf,0,BUFSIZ);
if((len=read(orig_sock,cbuf,BUFSIZ))>0)
{
//server prompt for directory
if (GetDirectoryMessage(cbuf)==1)
{
//DIRECTORY
getcwd(buf,BUFSIZ);
//from char 14 till end, move to front
tint2=strlen(buf);
for (tint1=14;tint1<=tint2;tint1++) buf[tint1-14]=buf[tint1];
strcat(buf,"/");
strcpy(tch1,"/home");
strcat(tch1,buf);
strcpy(buf,tch1);
write(orig_sock,buf,strlen(buf));
}
//server prompt for copying
else if (CopyFile(cbuf)==1)
{
sscanf(cbuf,"%s %s %s",tch3,tch1,tch2);
//should fork and let child do copying of file to receiver's directory
cpid=fork();
if (cpid==0) //child
{
argin[0]="cp";
argin[3]=(char*)0;
execlp("cp",argin[0],tch1,tch2,argin[3]);
exit(3);
}
else //parent, wait for child to finish copying
{
if (wait(&status)<0)
{
printf("Error copying file to client!\n");
write(fileno(stdout),"> ",3);
}
}
//set chmod
cpid=fork();
if (cpid==0) //child
{
argin[0]="chmod";
argin[1]="a+rwx";
argin[3]=(char*)0;
execlp("chmod",argin[0],argin[1],tch2,argin[3]);
exit(3);
}
else //parent, wait for child to finish chmoding
{
if (wait(&status)<0)
{
printf("Error changing file permission on sent file!\n");
write(fileno(stdout),"> ",3);
}
else
{
printf("File <%s> sent!\n",tch1);
write(fileno(stdout),"> ",3);
}

}
}
else
{
write(fileno(stdout),"\n",1);
write(fileno(stdout),cbuf,len);
write(fileno(stdout),"> ",3);
}
}

memset(&buf,0,BUFSIZ);
if((len=read(fileno(stdin),buf,BUFSIZ))>0)
{
whichcmd=WhichCommand(buf);
//clear screen
if (whichcmd==1) ClearScreen();
//send file
else if (whichcmd==2)
{
write(orig_sock,buf,len);
}
//get own id
else if (whichcmd==3)
{
//get own id from server in the form "/ownid : ???"
write(orig_sock,buf,len);
while (len=read(orig_sock,cbuf,BUFSIZ)<=0);
sscanf(cbuf,"%s %s %s",tch1,tch2,tch3);
printf("Server : own id is %s\n",tch3);
printf("> ");
fflush(stdout);
}
else if (whichcmd==0)
{
write(orig_sock,buf,len);
write(fileno(stdout),"> ",3);
fflush(stdout);
sleep(1);
}
}

}while(buf[0]!='.');


close(orig_sock);
exit(0);
}
小
小鱼儿〖四国研究所〗
2001-04-13 07:18
s7.c (>gcc -i s7.c server)
#include <stdio.h>
#include <signal.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <fcntl.h>
#include <sys/time.h>
extern errno;

#define PORT 22222
#define MAX_CLIENT 5
static char buf[BUFSIZ];

//follow "c7.c"
//-1 non command
//1 clear screen
//2 send file
//3 get own id
int WhichCommand(char usercmd[])
{
char tbuf[201];
char tbuf1[101];
char tbuf2[101];
char tbuf3[101];
int i;

//convert to upper case
strncpy(tbuf,usercmd,200);
for (i=0; i<strlen(tbuf); i++) tbuf[i]=toupper(tbuf[i]);

//extract command
//CLEAR
if (strcmp(tbuf,"/CLEAR\n")==0) return 1;

//SEND
sscanf(tbuf,"%s",tbuf1);
if (strcmp(tbuf1,"/SEND")==0) return 2;

//OWNID
sscanf(tbuf,"%s",tbuf1);
if (strcmp(tbuf1,"/OWNID")==0) return 3;

return 0;
}

///////////////////////////////////////////////

//extract the client number to send to
//return client number if successful,
//0 or negative number returned if unsuccessful
int GetReceiverClientNo(char *msg)
{
char t1[100],t2[100];
//less than 2 words in message
if (sscanf(msg,"%s %s",t1,t2)<2) return -1;
return atoi(t2);
}

///////////////////////////////////////////////

int getuser(char *input)
{
int i,count=0;
char ctemp[50];

if(!isdigit(input[1]))
return 0;

while(!isdigit(input[count]))count++;
i=0;
while(isdigit(input[count]))
{
ctemp[i++]=input[count++];
}
ctemp[i]='\0';
return atoi(ctemp);
}

///////////////////////////////////////////////

void set_unblock(int sock)
{
if(fcntl(sock,F_SETFL,FNDELAY)<0)
{
perror("File control");
exit(2);
}
}

///////////////////////////////////////////////

void form_message(int i,char *input,char *result)
{
char temp[100];
strcpy(temp,"Client");
strcat(temp,ltoa(((long)i+1)));
strcat(temp," > ");
strcat(temp,input);
write(fileno(stdout),temp,strlen(temp));
strcpy(result,temp);
}

///////////////////////////////////////////////

void disp_time(int fd)
{
struct tm *tm_ptr;
time_t atime;

(void) time(&atime);
tm_ptr = localtime(&atime);
if (tm_ptr->tm_hour>=10)
{
write(fd, ltoa(tm_ptr->tm_hour), strlen(ltoa(tm_ptr->tm_hour)));
}
else
{
write(fd, "0", 1);
write(fd, ltoa(tm_ptr->tm_hour), strlen(ltoa(tm_ptr->tm_hour)));
}
write(fd,":",1);
if (tm_ptr->tm_min>=10)
{
write(fd, ltoa(tm_ptr->tm_min), strlen(ltoa(tm_ptr->tm_min)));
}
else
{
write(fd, "0", 1);
write(fd, ltoa(tm_ptr->tm_min), strlen(ltoa(tm_ptr->tm_min)));
}
write(fd,":",1);
if (tm_ptr->tm_sec>=10)
{
write(fd, ltoa(tm_ptr->tm_sec), strlen(ltoa(tm_ptr->tm_sec)));
}
else
{
write(fd, "0", 1);
write(fd, ltoa(tm_ptr->tm_sec), strlen(ltoa(tm_ptr->tm_sec)));
}
}

///////////////////////////////////////////////

void store(char* data, int fd)
{
disp_time(fd);
write(fd," : ",3) ;
write(fd,data,strlen(data));
}

///////////////////////////////////////////////

main(void)
{
int tlen,fd,orig_sock,new_sock,clnt_len,len,i,count,loop_count;
int sock[MAX_CLIENT][2],receiver;
char cbuf[100];
struct sockaddr_in serv_adr,com_adr,clnt_adr;
int reserve[BUFSIZ];
int reserve_pt;
int tmp;
int goback=0;

int t1;
char tbuf1[100],tbuf2[100],tbuf3[100],tbuf4[100];


for (tmp=0;tmp<BUFSIZ;tmp++) reserve[tmp]=-1;
reserve_pt=0;
tmp=0;

count=0;
tlen=strlen(ltoa(time(NULL)));

if((fd=open("logdata",O_WRONLY|O_APPEND|O_CREAT,0644))==-1)
{
write(fileno(stdout),"Log file error",14);
exit(1);
}
lseek(fd,(off_t)0,SEEK_END);

if((orig_sock=socket(AF_INET,SOCK_STREAM,0))<0)
{
perror("Server socket");
exit(1);
}

set_unblock(orig_sock);

memset(&serv_adr,0,sizeof(serv_adr));
serv_adr.sin_family=AF_INET;
serv_adr.sin_addr.s_addr=htonl(INADDR_ANY);
serv_adr.sin_port=htons(PORT);

if(bind(orig_sock,(struct sockaddr *)&serv_adr,sizeof(serv_adr))<0)
{
perror("Server bind");
exit(3);
}

if(listen(orig_sock,5)<0)
{
perror("listen error");
exit(4);
}

do
{
do
{

memset(&buf,0,BUFSIZ);

for(i=0;i<count;i++)
if((len=read(sock[i][1],buf,BUFSIZ))>0)
{
form_message(i,buf,cbuf);
store(cbuf,fd);
if(buf[0]=='Q')
for(loop_count=0;loop_count<count;loop_count++)
{
if(loop_count!=i)
{
write(sock[loop_count][1],cbuf,strlen(cbuf));
}
}
else
if(buf[0]=='A')
{
if((receiver=getuser(buf))>0)
{
write(sock[receiver-1][1],cbuf,strlen(cbuf));
}
}
else
if(buf[0]=='.')
{
if (count==tmp)
{
count--;
}
else
{
reserve[reserve_pt]=i;
reserve_pt++;
}
printf("Client %d left ...\n",i+1);
printf("%d client(s) right now !\n",count-reserve_pt);
write(fd,"Client ",7);
write(fd,ltoa(i+1),strlen(ltoa(i+1)));
write(fd," left server at time ",21);
disp_time(fd);
write(fd,"\n",1);
if(reserve_pt==count)
{
count=0;
reserve_pt=0;
printf("No clients left on server now !\n");
disp_time(fd);
write(fd," : No clients left in server !",30);
write(fd,"\n",1);
}
}
//send file
else if (WhichCommand(buf)==2)
{
//check it is not sending to itself
sscanf(buf,"%s %s",tbuf1,tbuf3);
if (i+1==atoi(tbuf3))
{
sprintf(cbuf,"Error : sending to ownself\n");
write(sock[i][1],cbuf,strlen(cbuf));
}
else
{
strcpy(cbuf,"/getdirectory");
write(sock[i][1],cbuf,strlen(cbuf));
//store sender's directory in tbuf1
while ((len=read(sock[i][1],tbuf1,BUFSIZ))<=0) sleep(1);
strcpy(cbuf,"/getdirectory");
write(sock[atoi(tbuf3)-1][1],cbuf,strlen(cbuf));
//store receiver's directory in tbuf2
while ((len=read(sock[atoi(tbuf3)-1][1],tbuf2,BUFSIZ))<=0) sleep(1);
//ask client to copy file
sscanf(buf,"%s %s %s",cbuf,tbuf4,tbuf3);//tbuf3 has filename
sprintf(cbuf,"/copy %s%s %s%s",tbuf1,tbuf3,tbuf2,tbuf3);
write(sock[i][1],cbuf,strlen(cbuf));
}
}
//ownid
else if (WhichCommand(buf)==3)
{
sprintf(cbuf,"%s %d","/ownid :",i+1);
write(sock[i][1],cbuf,strlen(cbuf));
}

}
}while((new_sock=accept(orig_sock,(struct sockaddr*)&clnt_adr,&clnt_len))<0);

if ((count==MAX_CLIENT)&&(reserve_pt==0))
{
write(new_sock," Server overload! Unable to connect! ",37);
close(new_sock);
goback=1;
}

if (goback==0)
{


if (reserve_pt>0)
{
tmp=reserve[reserve_pt-1];
reserve[reserve_pt-1]=-1;
reserve_pt--;
}
else
{
tmp=count;
count++;
}

printf("Client %d joined server ...\n",tmp+1);

write(fd,"Client ",7);
write(fd,ltoa(tmp+1),strlen(ltoa(tmp+1)));
write(fd," joined server at time ",23);
disp_time(fd);
write(fd,"\n",1);

if(socketpair(AF_UNIX,SOCK_STREAM,0,sock[tmp])<0)
{
perror("Socket pair generation error");
close(orig_sock);
exit(6);
}
for(i=0;i<2;i++)
set_unblock(sock[tmp][i]);

if(fork()==0)
{
close(sock[tmp][1]);

set_unblock(new_sock);
do
{
memset(&buf,0,BUFSIZ);
if((len=read(new_sock,buf,BUFSIZ))>0)
{
if(buf[0]=='.')
{
if (count==tmp)
{
count--;
}
else
{
reserve[reserve_pt]=i;
reserve_pt++;
}

close(new_sock);
//write(sock[count][0],buf,len);
write(sock[tmp][0],buf,len);
exit(9);
}
write(sock[tmp][0],buf,len);
//write(sock[count][0],buf,len);
}

if((len=read(sock[tmp][0],buf,BUFSIZ))>0)
{
write(new_sock,buf,len);
}

}while(1);
}else close(new_sock);

close(sock[tmp][0]);
}

goback=0;

}while(1);
close(fd);
}
叶
叶@四国研究所
2001-04-13 20:52
高手啊高手,看不懂啊看不懂,原想说蒜蒜程序太少注释,现发现小鱼儿竟是一句注释没有。:)
心迹所到之处一定比足迹所到更为遥远与辽阔......

四国研究所
小
小菜@/dev/null
2001-04-13 23:30
呵呵。。
小鱼儿,这个东东系不系侬的计算机网络课的作业呀?:)偶算明白侬组撒在那些做作业的日子里每天到早上两、三点的原因乐,太牛x:)) hehe

1 / 1

登录后回复。