怎么进行Java Socket编程相关源代码的介绍
短信预约 -IT技能 免费直播动态提醒
今天就跟大家聊聊有关怎么进行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编程相关源代码的介绍有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注编程网行业资讯频道,感谢大家的支持。
免责声明:
① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。
② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341