java socket的简单模型
服务器端代码:
/**
*
* @author:李星星
* @date:Dec 14, 2010
*/
package com.lixx;
import java.io.BufferedReader;
import java.net.ServerSocket;
public class SocketServer extends Thread{
private java.net.ServerSocket ss;
private java.net.Socket s;
@Override
public void run() {
try{
while(true){
this.s=this.ss.accept();
java.io.BufferedReader reader =
new BufferedReader(
new java.io.InputStreamReader(
s.getInputStream()));
String str=reader.readLine();
System.out.println("开始接受数据:");
while(str!=null){
System.out.println("读了一行");
System.out.println(str);
str=reader.readLine();
}
reader.close();
this.s.close();
}
}catch(Exception ex){
ex.printStackTrace();
}
}
public SocketServer(int port){
try{
System.out.println("服务端启动.......");
this.ss=new ServerSocket(port);
}catch(Exception ex){
ex.printStackTrace();
}
}
public static void main(String[] args){
Thread t=new SocketServer(8888);
t.start();
}
}
客户端代码:
/**
*
* @author:李星星
* @date:Dec 14, 2010
*/
package com.lixx;
import java.io.BufferedReader;
public class SocketClient {
public static void main(String[] args)throws Exception {
java.net.Socket s=new java.net.Socket("127.0.0.1",8888);
java.io.BufferedWriter out=new java.io.BufferedWriter(
new java.io.OutputStreamWriter(
new java.io.BufferedOutputStream(s.getOutputStream())));
java.io.BufferedReader reader=new BufferedReader(
new java.io.InputStreamReader(System.in));
String str=reader.readLine();
while(!"exit".equals(str)){
out.write(str + "\n");
out.flush();
str=reader.readLine();
}
reader.close();
out.close();
}
}