看到現在很多朋友都在問socket的問題,因此自己寫了個用socket搭建服務器的基礎程序供大家參考。程序只實現了簡單的接收然後廣播。
小弟水平有限,還望大家不吝賜教。程序如下:
import Java.Net.*;
import Java.io.*;
import Java.util.*;
public class SocketServer2 extends Thread{
Vector v = null;
ServerSocket ss = null;
public SocketServer2() {
v = new Vector();
try{
ss = new ServerSocket(8000);
}catch(Exception e){System.out.println(e);}
this.start();
}
public static void main(String[] args) {
new SocketServer2();
}
public void run()
{
try{
while(true)
{
/* 為各個客戶端建立連接並用Vector存儲相關信息,據<thinking in Java>上說ArrayList更好,不過我對ArrayList不熟,就將就用Vector了 */
Socket sc = ss.accept();
InputStream is = sc.getInputStream();
OutputStream os = sc.getOutputStream() ;
Exchange ct = new Exchange(this,is,os);
v.addElement(ct);
}
}
catch(Exception e){}
}
public void sendMsg(String str){
/* 利用存儲的各個流信息進行廣播 */
for(int i=0;i<v.size();i++){
Exchange eg = (Exchange)v.elementAt(i);
try{
System.out.println(str);
eg.os.write((str+"\n").getBytes());
}catch(Exception e){}
}
}
}
/* 每個線程控制一個連接,獨自實現接收和廣播 */
class Exchange extends Thread{
SocketServer2 s=null;
InputStream is = null;
OutputStream os = null;
Exchange(SocketServer2 s,
InputStream is,
OutputStream os){
this.s = s;
this.is = is;
this.os = os;
this.start();
}
public void run(){
while(true){
try{
DataInputStream dis = new DataInputStream(is) ;
String sb="";
int c=0;
while (((c = is.read()) != '\n') && (c != -1)) {
sb=sb+(char)c;
}
if (c == -1) {
break;
}
s.sendMsg(sb);
}
catch(Exception e){System.out.println(e);}
}
}
}