网络编程——服务器端
Posted 风少凌云
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了网络编程——服务器端相关的知识,希望对你有一定的参考价值。
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();
}
}
}
}
}
以上是关于网络编程——服务器端的主要内容,如果未能解决你的问题,请参考以下文章