import java.net.*;
import java.io.*;
public class MultiUser extends Thread{
private Socket client;
public MultiUser(Socket c){
this.client=c;
}
public void run(){
try{
BufferedReader in=new BufferedReader(new InputStreamReader(client.getInputStream()));
PrintWriter out=new PrintWriter(client.getOutputStream());
//Mutil User but can parallel
while(true){
String str=in.readLine();
System.out.println(str);
out.println("has receive....");
out.flush();
if(str.equals("end"))
break;
}
client.close();
}catch(IOException ex){
}finally{
}
}
public static void main(String[] args)throws IOException{
ServerSocket server=new ServerSocket(5678);
while(true){
//transfer location change Single User or Multi User
MultiUser mu=new MultiUser(server.accept());
mu.start();
}
}
}
客户端代码:
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(),5678);
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(in.readLine());
}
Server.close();
}
}
这段程序是接受客户的键盘输入,并把信息输出到服务端。并把"end"作为退出的命令
以上程序完成了两台计算机的简单通信。