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编程的详细介绍。希望大家有所帮助。
【编辑推荐】