服务
package com.kinth.basic.timetask.job.donghuan.socket;import java.io.IOException;import java.net.ServerSocket;import java.net.Socket;public class SocketServerThread extends Thread { public void run() { try { serverSocket = new ServerSocket(8080); while(serverSocket != null){ //循环监听客户端的连接 Socket socket = serverSocket.accept(); //新建一个线程ServerSocket,并开启 new SocketClientConnThread(socket).start(); } } catch (IOException e) { e.printStackTrace(); } } }
处理客户端消息
import java.io.BufferedReader;import java.io.InputStreamReader;import java.io.PrintWriter;import java.net.Socket;public class SocketClientConnThread extends Thread { private Socket socket; public SocketClientConnThread(Socket socket) { this.socket = socket; } public void run() { BufferedReader is = null; PrintWriter os = null; try { while(socket != null){ //接收客户端信息 is = new BufferedReader(new InputStreamReader(socket.getInputStream(),"GB2312")); String str = is.readLine(); if(str != null && !str.equals("") && !str.equals("null")){ System.out.println(str ); //往客户端发送信息 os = new PrintWriter(socket.getOutputStream());//由Socket对象得到输出流,并构造PrintWriter对象 //发送更新信息 os.println("OK"); os.flush(); }else{ Thread.sleep(3000); SocketUtil.close(socket, is, os); } } } catch (Exception e) { e.printStackTrace(); SocketUtil.close(socket, is, os); } }}
测试服务
import java.io.BufferedReader;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.io.OutputStream;import java.io.PrintWriter;import java.net.Socket;import java.net.UnknownHostException;/** ** 基于socket通讯-客户端 *
*/public class Client { public static void main(String[] args) { Socket socket = null; OutputStream os = null; PrintWriter pw = null; InputStream is = null; InputStreamReader isr = null; BufferedReader br = null; try { socket = new Socket("IP地址", 8080); // 获取输出流向服务端写入数据 os = socket.getOutputStream(); pw = new PrintWriter(os); pw.write("用户名:admin 密码:123"); pw.flush(); socket.shutdownOutput(); // 获取输入流接受服务端返回的信息 is = socket.getInputStream(); isr = new InputStreamReader(is); br = new BufferedReader(isr); String message = null; while ((message = br.readLine()) != null) { System.out.println("服务器说:" + message); } socket.shutdownInput(); } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { if (br != null) { br.close(); } } catch (IOException e) { e.printStackTrace(); } try { if (isr != null) { isr.close(); } } catch (IOException e) { e.printStackTrace(); } try { if (is != null) { is.close(); } } catch (IOException e) { e.printStackTrace(); } if (pw != null) { pw.close(); } try { if (os != null) { os.close(); } } catch (IOException e) { e.printStackTrace(); } try { if (socket != null) { socket.close(); } } catch (IOException e) { e.printStackTrace(); } } }}