看到现在很多朋友都在问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);}
}
}
}
(出处:http://www.VeVb.com)
新闻热点
疑难解答