怎么进行JavaSocket编程相关源代码的介绍
今天就跟大家聊聊有关怎么进行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编程相关源代码的介绍有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注创新互联行业资讯频道,感谢大家的支持。
网站名称:怎么进行JavaSocket编程相关源代码的介绍
本文路径:http://scyanting.com/article/gosgoo.html