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://www.mswzjz.cn/qtweb/news4/333154.html
攀枝花网站建设、攀枝花网站运维推广公司-贝锐智能,是专注品牌与效果的网络营销公司;服务项目有等
声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 贝锐智能