📄 server.java
字号:
import java.io.*;
import java.net.*;
class server{
ServerSocket server_socket;
String user[];
static int client_counter=0;
InputStream net_input[];
OutputStream net_output[];
public static void main(String args[]){
new server();
}
public server(){
user=new String[2];
net_input=new InputStream[2];
net_output=new OutputStream[2];
try{
server_socket=new ServerSocket(1111);
}
catch(IOException e){
System.out.println("Error in server socket");
return;
}
System.out.println("waiting for users...");
while(true){
try{
Socket socket=server_socket.accept();
service_request(socket);
}
catch(IOException e){
System.out.println("Exception:<"+e+">");
break;
}
}
}
public void service_request(Socket socket){
InputStream input;
OutputStream output;
try{
input=socket.getInputStream();
output=socket.getOutputStream();
}
catch(IOException e){
System.out.println("Unable to get input/output streams");
return;
}
if(client_counter>=2){
write_net_output(output,"There are already two clients");
return;
}
net_input[client_counter]=input;
net_output[client_counter]=output;
user[client_counter]=read_net_input_line(input);
System.out.println(user[client_counter]+" Connected!"+socket.toString());
(new reader(this,client_counter)).start();
int c=client_counter++;
}
String read_net_input_line(InputStream input){
String line="";
String c;
c=read_net_input(input);
while((byte)c.charAt(0)!=10){
line=line+c;
c=read_net_input(input);
}
return line;
}
String read_net_input(InputStream input){
byte bytes[];
int number_of_bytes;
try{
bytes=new byte[1];
number_of_bytes=input.read(bytes,0,1);
if(number_of_bytes>0){
String s=new String(bytes,0,0,number_of_bytes);
return(s);
}
else
return null;
}
catch(IOException e){
return null;
}
}
void write_net_output(OutputStream output,String string){
byte byte_array[];
int length=string.length();
byte_array=new byte[length];
string.getBytes(0,length,byte_array,0);
try{
output.write(byte_array);
}
catch(IOException e){;}
}
}
class reader extends Thread{
server s;
int index;
public reader(server s, int index){
this.s=s;
this.index=index;
}
public void run(){
setPriority(MIN_PRIORITY);
s.write_net_output(s.net_output[index],"WAIT");
while (s.client_counter<2){
s.write_net_output(s.net_output[index]," GO...");
while(true){
String string=s.read_net_input(s.net_input[index]);
if(string==null) break;
System.out.println(s.user[index]+":"+string);
s.write_net_output(s.net_output[(index+1)%2],string);
}
System.out.println(s.user[index]+" has disconnected.");
s.user[index]=null;
if(--s.client_counter==0)
System.exit(0);
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -