日期:2014-05-17 浏览次数:20742 次
ServerSocket server = new ServerSocket(1000);
String str;
System.out.println("服务端开启。。。");
while(true) {
Socket socket = server.accept(); //一旦客户端(请求道ip和端口阻塞就结束)Socket socket = new Socket(ip, 1000);
ip = socket.getInetAddress().getHostAddress();
new ServerInput(socket, ip).start();//启动子线程
//new ServerOutput(socket, "sxsx").start();//启动子线程
}
package server;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
public class ServerInput extends Thread{
Socket socket;
StringBuffer sb;
String ip;
public ServerInput(Socket socket){
this.socket = socket;
sb = new StringBuffer(); //sb作为存储信息的缓存
}
public ServerInput(Socket socket, String ip){
this.socket = socket;
sb = new StringBuffer(); //sb作为存储信息的缓存
this.ip = ip;
}
@Override
public void run() {
// TODO Auto-generated method stub
try {
InputStream in = socket.getInputStream(); //获取读取流
byte[] b = new byte[1024];
int length = in.read(b); //为阻塞 一旦客服端发送消息 就会往下执行
System.out.println("ss");
if(length != -1) {
sb.append(new String(b,0,length)); //讲读取的字符给sb
}
in.close();
System.out.println(sb.toString());
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("ip:"+ip + "离开");
}
}
}
while (true) {
Socket client = server.accept(); //阻塞
OutputStream out = client.getOutputStream();
//out.write("server to client : hello".getBytes());
out.flush();
out.close();
client.close();
sleep(1000);
}
while (true) {
Socket client = new Socket("localhost", 8888);
InputStream in = client.getInputStream();
byte[] buff = new byte[4096];
StringBuffer sbuff = new StringBuffer();
int len = 0;
while ((len = in.read(buff)) != -1) { //没阻塞?
sbuff.append(new String(buff, 0, len));
}
in.close();
client.close();
System.out.println(sbuff.toString() + "test");
sleep(1000);
}