码迷,mamicode.com
首页 > 其他好文 > 详细

网络编程——服务器端

时间:2017-04-29 15:14:22      阅读:128      评论:0      收藏:0      [点我收藏+]

标签:tar   except   处理   创建   取数   编程   eth   his   test   

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.io.BufferedReader;
import java.io.InputStreamReader;


public class TestServer {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
//1、创建服务器监听器
ServerSocket server = null;
try {
server = new ServerSocket(9527);
//2、开始监听
System.out.println("开始监听......");
while(true){
Socket socket = server.accept();//accept会进入阻塞状态,一旦有消息发送过来,就返回Socket对象
//3、开启子线程进行消息处理
new ProcessThread(socket);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally{
if(server != null){
try {
server.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}



}

}

public class ProcessThread extends Thread{
private Socket socket;

public ProcessThread(Socket socket){
this.socket = socket;
this.start();
}

@Override
public void run() {
// TODO Auto-generated method stub
//3、从Socket的InputStream取数据
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String msg = br.readLine();
System.out.println("接收的消息:" + msg);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally{
if(br != null){
try {
br.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}
if(socket != null){
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

}

}

网络编程——服务器端

标签:tar   except   处理   创建   取数   编程   eth   his   test   

原文地址:http://www.cnblogs.com/fengshaolingyun/p/6785138.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!