基于Sockt 服务器端简单实现
package com.socket.t1;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class ChatServer {
/**
* @param args
*/
public void setUpServer(int port){
try {
ServerSocket servertSocket = new ServerSocket(port);
System.out.println("服务器创建成功,端口:"+port);
//让服务器进入等待状态
while(true){
Socket client = servertSocket.accept();
System.out.println("Incoming client:"+client.getRemoteSocketAddress());
processChat(client);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void processChat(Socket client) {
// TODO Auto-generated method stub
try {
//从连接上得到一个输入输出流
OutputStream out = client.getOutputStream();
InputStream in = client.getInputStream();
String s = " welcome to here/r/n";
byte data [] =s.getBytes();//取得组成这个字符串的字节
out.write(data);//输出
out.flush();//强制输出
String inputStr = readString(in);
while(!inputStr.equals("bye")){
System.out.println("客户端说:"+inputStr);
s = "服务器收到:"+inputStr+"/r/n";
data =s.getBytes();//取得组成这个字符串的字节
out.write(data);//输出
out.flush();//强制输出
inputStr = readString(in);
}
s = "欢迎再来!"+"/r/n";
data = s.getBytes();
out.write(data);
out.flush();
client.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private String readString(InputStream in) {
// TODO Auto-generated method stub
String str = null;
try {
StringBuffer sb = new StringBuffer();
char c= 0;
while(c!=13){
//遇到一个换行,就是一句话。
int i = in.read();//读取客户端发送的字节
c = (char)i;//转成char类型
sb.append(c);//加入到字符串缓冲区
}
str = sb.toString().trim();
} catch (Exception e) {
// TODO: handle exception
}
return str;
}
public static void main(String[] args) {
ChatServer cs = new ChatServer();
cs.setUpServer(8080);
}
}
//window下通过 telnet localhost 8088 可连接到此服务器上,win7默认关闭此功能,可自己在控制面板中打开
posted on 2011-06-10 19:58 android开发实例 阅读(145) 评论(0) 编辑 收藏 举报