这是一个比较简单的例子来说明socket编程,服务器端使用了多线程来监听客户端。
服务器端的代码:
package SocketTest;
import java.io.*;
import java.net.*;
import java.util.*;
class SocketServer{
public SocketServer(){
Socket incoming;
ServerSocket so;
try{
so= new ServerSocket(8001);
System.out.println("等待客户端连接。");
while(true){
try{
incoming =
so.accept( );
System.out.println("已连接客户端。");
GetInfo gi=new
GetInfo(incoming);//调用线程
} catch (IOException e){
e.printStackTrace();
}
}
}catch (IOException e){
e.printStackTrace();
}
}
public static void main(String[] args){
new SocketServer();
}
private static class GetInfo implements Runnable{ //线程类
private Socket incoming;
private String s=null;
private BufferedReader b;
Thread t;
public GetInfo(Socket incoming){
try{
this.incoming=incoming;
b=new BufferedReader(new
InputStreamReader(incoming.getInputStream()));
t=new Thread(this);
t.start();
}catch(IOException e){
e.printStackTrace();
}
}
public void run(){
try{
while (true){
s=b.readLine();
System.out.println(s);
if(s.equals("end")){
break;
}
}
}catch(IOException e){
e.printStackTrace();
}
}
}
}
客户端的代码:
package SocketTest;
import java.io.*;
import java.net.*;
import java.util.*;
public class SocketClient{
public static void main(String[] args){
try{
Socket so = new Socket("localhost", 8001);
System.out.println("连接服务器。");
BufferedReader b=new BufferedReader(new
InputStreamReader(System.in));
OutputStream outStream = so.getOutputStream();
PrintWriter out = new PrintWriter(outStream);
String s=null;
while (true){
s=b.readLine();
out.println("Client:"+s);
out.flush();
if(s.equals("end")){
break;
}
}
}catch (IOException e){
e.printStackTrace();
}
}
}
posted on 2005-10-10 14:04
千山鸟飞绝 阅读(2686)
评论(2) 编辑 收藏 所属分类:
J2SE