Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to implement a Socket operation tool class in JAVA

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/02 Report--

JAVA how to achieve a Socket operation tool class, many novices are not very clear about this, in order to help you solve this problem, the following editor will explain in detail for you, people with this need can come to learn, I hope you can get something.

Socket operation tool class import java.io.*;import java.net.ServerSocket;import java.net.Socket;import java.net.UnknownHostException;/** * @ author JL * @ version V1.0 * @ Description with java.net.Socket Socket operation tool class * / public class SocketUtils {private static final String ENCODING = "UTF-8" with java.net.Socket; public static void listen (final int port, String content, SocketFunction function) throws IOException {ServerSocket serverSocket = null Socket socket = null; try {serverSocket = createServer (port); socket = createServerSocket (serverSocket); / / usually after the socket connection is obtained, a thread is assigned to process the client WorkClass workClass = new WorkClass (socket, content, function); workClass.work ();} catch (IOException ioe) {ioe.printStackTrace () Throw ioe;} finally {clientClose (socket); / / close server serverClose (serverSocket);}} static class WorkClass {private Socket socket; private String content; private SocketFunction function; public WorkClass (Socket socket, String content, SocketFunction function) {this.socket = socket; this.content = content This.function = function;} public void work () throws IOException {String msg = null; InputStream in = null; OutputStream out = null; try {in = socket.getInputStream (); msg = input (in); out = socket.getOutputStream (); output (out, content) Function.callback (msg);} finally {/ / closes the input / output stream streamClose (in, out);} public static void send (String host, int port, String content, SocketFunction function) throws IOException {Socket socket = null; String msg = null; InputStream in = null; OutputStream out = null Try {socket = createClientSocket (host, port); out = socket.getOutputStream (); output (out, content); socket.shutdownOutput (); / / after exporting, you need to close the output channel of socket, indicating that the output to the server in = socket.getInputStream (); msg = input (in); function.callback (msg) } catch (UnknownHostException uhe) {uhe.printStackTrace (); throw new IOException ("Host connection creation exception:" + uhe.getMessage ());} catch (IOException ioe) {ioe.printStackTrace (); throw ioe;} finally {streamClose (in, out); clientClose (socket) }} public static void streamClose (InputStream in, OutputStream out) {/ / IOUtils.closeQuietly (in); you can use the IOUtils utility class to close the stream if (in! = null) {try {in.close ();} catch (IOException ioe) {System.out.println ("close input stream exception:" + ioe.getMessage ()) }} if (out! = null) {try {out.flush (); out.close ();} catch (IOException ioe) {System.out.println ("close output stream exception:" + ioe.getMessage ()) }} private static ServerSocket createServer (int port) throws IOException {System.out.println ("listener port number:" + port); return new ServerSocket (port);} private static Socket createServerSocket (ServerSocket serverSocket) throws IOException {Socket socket = serverSocket.accept (); System.out.println ("get a client connection:" + socket.getInetAddress (). GetHostAddress ()); return socket } private static Socket createClientSocket (String host, int port) throws UnknownHostException, IOException {return new Socket (host, port);} private static void serverClose (ServerSocket server) {if (server! = null & &! server.isClosed ()) {try {server.close () } catch (IOException ioe) {System.out.println ("Service shutdown exception:" + ioe.getMessage ());} private static void clientClose (Socket socket) {if (socket! = null & &! socket.isClosed ()) {try {socket.close () } catch (IOException ioe) {System.out.println ("Socket close exception:" + ioe.getMessage ());} public static OutputStream output (OutputStream out, String content) throws IOException {try {out.write (content.getBytes (ENCODING));} finally {return out } public static String input (InputStream in) throws IOException {int len; char [] b = new char [1024]; StringBuilder sb = new StringBuilder (); BufferedReader reader Try {/ / is mainly character stream. If byte stream is needed, BufferedReader and InputStreamReader are not needed. You can directly obtain or use the corresponding buffer wrapper class reader = new BufferedReader (new InputStreamReader (in, ENCODING)) from InputStream; while ((len = reader.read (b))! =-1) {sb.append (b, 0, len) } / / reader.close ();} finally {} return sb.toString ();} public interface SocketFunction {void callback (String msg);} public static void main (String [] args) throws IOException {String data = "this is test data:" / / when testing, start send and listen methods / / client / / send separately ("127.0.0.1", 8111, "this is client test", new SocketFunction () {/ / @ Override// public void callback (String msg) {/ / System.out.println (data + msg); / /} / /})) / / server listen (8111, "this is server test", new SocketFunction () {@ Override public void callback (String msg) {System.out.println (data + msg);}});}}

Description:

Anyone who has worked on a project knows that many of the reusable code blocks or useful tool classes that have been written have not been sorted out, and when needed, they have to open the project and look it up, although the function development is not difficult, but it takes time and cost to write and test, so it is better to keep the wheel for everyone to use.

1. The wheel can have: this component really doesn't exist when you need it.

two。 The wheel is not there when I need it: every technology or tool has its project background. When the code is written in the project, I know there is this thing. When you change a project or company, there is no backup or record. When you are gone, you have to take the time to type it again.

3. I don't know if I'm building wheels: in most cases, it's hard for beginners to tell if they're remaking wheels. In fact, making wheels is not my goal. My goal is to complete the task, the faster the task is completed, the better, and the higher the quality, the better. Instead of judging whether you are building wheels or not.

4. Don't want to spend time building wheels over and over again: sometimes you come across something that is not difficult but takes a lot of time. Of course, there are ready-made wheels that take the least time.

5. I just want to learn wheels: beginners don't build wheels over and over again, but learn to improve their knowledge and skills.

Is it helpful for you to read the above content? If you want to know more about the relevant knowledge or read more related articles, please follow the industry information channel, thank you for your support.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report