今天就跟大家聊聊有关怎么进行Java Socket编程相关源代码的介绍,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。
Java Socket编程在不断发展中有不少的问题存在,下面我们就详细的看看如何才能更好的使用这个代码。接下来我们就看看相关的源代码介绍。
源代码介绍:
MyServer.java import java.io.IOException; import java.io.InputStream; import java.net.ServerSocket; import java.net.Socket; public class MyServer extends Thread { private int serverPort; private int maxConnection; public MyServer(int serverPort, int maxConnection) { this.serverPort = serverPort; this.maxConnection = maxConnection; } @Override public void run() { ServerSocket serverSocket = null; Socket socket = null; try { serverSocket = new ServerSocket(serverPort, maxConnection); socket = serverSocket.accept(); new ServerProcess(socket).start(); } catch (IOException e) { e.printStackTrace(); System.exit(1); } finally { if (serverSocket != null) { try { serverSocket.close(); } catch (IOException e) { e.printStackTrace(); System.exit(1); } } } } private class ServerProcess extends Thread { private Socket socket; public ServerProcess(Socket socket) { this.socket = socket; } @Override public void run() { InputStream stream = null; byte buffer[] = new byte[1024]; int length; StringBuffer recvMessage = new StringBuffer(); try { stream = socket.getInputStream(); while (true) { length = stream.read(buffer); if (length > 0) { recvMessage.append(new String(buffer, 0, length)); } else { break; } } System.out.println(recvMessage.toString()); } catch (IOException e) { e.printStackTrace(); } } } } MyClient.java import java.io.IOException; import java.io.OutputStream; import java.net.Socket; public class MyClient { private String serverAddress; private int serverPort; public MyClient(String serverAddress, int serverPort) { this.serverAddress = serverAddress; this.serverPort = serverPort; } public boolean sendMessage(String message) { Socket socket = null; OutputStream stream = null; try { socket = new Socket(serverAddress, serverPort); stream = socket.getOutputStream(); stream.write(message.getBytes()); return true; } catch (IOException e) { e.printStackTrace(); return false; } finally { try { if (socket != null) { socket.close(); } if (stream != null) { stream.close(); } } catch (IOException e) { e.printStackTrace(); } } } } Main.java public class Main { public static void main(String[] args) { MyServer server = new MyServer(6001, 1); server.start(); MyClient client = new MyClient("localhost", 6001); client.sendMessage("Hello Tomorrow!!"); } }
Java Socket编程运行结果
Hello Tomorrow!!
看完上述内容,你们对怎么进行Java Socket编程相关源代码的介绍有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注亿速云行业资讯频道,感谢大家的支持。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。