這是一個比較簡單的例子來說明socket編程
服務器端的代碼
package SocketTest;
import java
import
import java
class SocketServer{
public SocketServer(){
Socket incoming;
ServerSocket so;
try{
so= new ServerSocket(
System
while(true){
try{
incoming = so
System
GetInfo gi=new GetInfo(incoming);//調用線程
} catch (IOException e){
e
}
}
}catch (IOException e){
e
}
}
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
b=new BufferedReader(new InputStreamReader(incoming
t=new Thread(this);
t
}catch(IOException e){
e
}
}
public void run(){
try{
while (true){
s=b
System
if(s
break;
}
}
}catch(IOException e){
e
}
}
}
}
客戶端的代碼
package SocketTest;
import java
import
import java
public class SocketClient{
public static void main(String[] args){
try{
Socket so = new Socket(
System
BufferedReader b=new BufferedReader(new InputStreamReader(System
OutputStream outStream = so
PrintWriter out = new PrintWriter(outStream);
String s=null;
while (true){
s=b
out
out
if(s
break;
}
}
}catch (IOException e){
e
}
}
}
From:http://tw.wingwit.com/Article/program/Java/gj/201311/27636.html