简单socket,实现简单的Echo功能

: 客户端从键盘输入 hi (当用户输出exit 退出程序),服务端响应为 hi(服务器要求为多线程)

 

 

解:服务器程序:

import Java.io.*;  

import Java.net.*;  
public class MyServer extends Thread{  
private Socket cq ;  
public MyServer(Socket cq)  
{  
this.cq = cq;  
}  
public void run()  
{  
try 
{  
BufferedReader in=new BufferedReader(new InputStreamReader(cq.getInputStream()));  
PrintWriter out=new PrintWriter(cq.getOutputStream());  
while(true)  
{  
String str=in.readLine();  
System.out.println(str);  
out.println(“message: “+str);  
out.flush();  
if(str.equals(“exit“))  
break;  
}  
}  
catch(IOException e)  
{  
System.out.println(e.message());  
}  
}  
public static void main(String[] args) throws IOException{  
ServerSocket server=new ServerSocket(8009);  
while(true)  
{  
Socket s=server.accept();  
new MyServer(s).start();  
}  
}  
} 

 

客户端程序:

import Java.net.*;  

import Java.io.*;  
public class MyClient{  
public static void main(String[] args)throws Exception  
{  
Socket server=new Socket(“localhost“,8009);  
BufferedReader in=new BufferedReader(new InputStreamReader(server.getInputStream()));  
PrintWriter out=new PrintWriter(server.getOutputStream());  
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));  
while(true)  
{  
String str=br.readLine();  
out.println(str);  
out.flush();  
if(str.equals(“exit“)){  
break;  
}  
System.out.println(in.readLine());  
}  
server.close();  
}  
} 

   

 

你可能感兴趣的:(java,thread,.net,socket)