SeverSocket就还好比站在酒店门口的迎宾小姐,而Socket好比顾客,迎宾小姐的工作就是迎接到来的顾客。
下面我们言归正传。
创建服务器:ServerSocket serverSocket = new ServerSocket(端口号);
我们可以创建一个工具类专门用来读数据
这里写代码片
public class Util(){
public static String read(InputStream in){
Byte[] b = new Byte[1024];
String content ="";
int length = -1;
try{
//返回-1读取完毕
while((length=in.reader(b))!=-1){
String value = new String(b,0,length);
if("#end#".equals(value)){
break;
}else{
content+=value;
}
}
return content
}catch(IOException e) {
e.printStackTrace();
}
}
public static void write(OutputStrem out,String message){
try{
while(true){
out.writer(message.getByte());
out.writer("#end#");
}
}catch(IOException e){
e.prinStackTrace();
}
}
}
下面我们来看看迎宾小姐与客户之间的关系
这里写代码片
//我的服务器
public class MyServer{
public static void main(String[]args){
System.out.println("服务器开启");
ServerSocket serverSocket = new ServerSocket(9898);
System.out.println("服务器等待连接");
Socket socket = serverSocket.accpt();
new ServerThread(socket);
InputStream in = serverSocket.getInputStream();
String content = Util.read(in);
System.out.println(content);
System.out.println("服务器结束");
}
}
下面我创建一个线程来专门来维护客户端,就好比迎宾小姐接待了一个客户就下班了吧,她应该重新回到工作岗位来迎接下一位客户
这里写代码片
public class ServerThread implemments Runnabel{
InputStream in;
public ServerThread(Socket socket){
this.socket = socket;
try{
in = socket.getInputStream();
//获取地址值
InetAddress address = soket.getInetAddress();
System.out.println("等待客户端连接"+address);
}catch(IOException e){
e.prinStackTrace();
}
in = socket.getInputStream();
//线程开启
new Thread(this).start();
}
public void run(){
while(true){
String content = Until.read(in);
System.out.printlm(content);
}
}
}
//我的客户端
这里写代码片
public static void main(String[]args){
Socket socket = new Socket("localhost",9898);
OutputStream out = socket.getOutputStream();
byte []b = "找个美女好过年".getBytes();
Util.write(out,b);
}
由于纯手工手写,不知道程序能运行起来,但逻辑是没有错的