快捷搜索:  as  2018  FtCWSyGV  С˵  test  xxx  Ψһ  w3viyKQx

和记娱乐App_机器人论坛



看到现在很多同伙都在问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存储相关信息,据上说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;和记娱乐Appi

Exchange eg = (Exchange)v.elementAt(i);

try{

System.out.println(str);

eg.os.write((str+"\n").getBytes());

}catch(Exception e){}

}

}

}

/* 每个线程节制一个连接,独自实现接管和广播 */

class Exchange extends和记娱乐App Thread{

SocketServer2 s=null;

InputStream is = null;

OutputStream os = null;

Exchange(SocketServer2 s,

InputStr和记娱乐Appeam is,

OutputStream os){

this.s = s;

this.is = is;

this.os = os;

this.start();

}和记娱乐App

public void run(){

while(true){

try{

DataInputStream dis = new DataInputStream(is) ;

String sb="";

int c=0;

while (((c = is.read()) != '\n') 和记娱乐App&& (c != -1)) {

sb=sb+(char)c;

}

if (c == -1) {

break;

}

s.sendMsg(sb);

}

catch(Exception e){System.out.println(e);}

}

}

}

您可能还会对下面的文章感兴趣: