首页 > 代码库 > 入门级的Java Socket代码

入门级的Java Socket代码

在男友手把手的指导下,写出第一个类似于“hello world”的socket程序。

男友要求:

1. 程序以命令行方式运行,在两台联网的电脑上分别运行;

2. 一台电脑的命令行中输入“程序名称 wait”,运行程序,进入监听状态;

3. 一台电脑的命令行中输入“程序名称 ip地址”,运行程序,连接另一台电脑;

4. 两台电脑均可发送接收消息。

分析流程图:

附代码:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
package mytalk;
 
import java.net.*;
import java.io.*;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
 
public class MyTalk {
    public static final int PORT = 12345;//监听的端口号   
 
    public static void main(String[] args) throws IOException{
        // 控制台输入服务器需要监听的端口号
        Scanner inputData = http://www.mamicode.com/new Scanner(System.in);
        ServerSocket serverSocket = null;
        Socket socket = null;
         
        if (args.length != 1) {
            throw new IllegalArgumentException("Parameter(s): wait or IP address.");
        }
        String str = args[0];
         
        if (str.equals("wait")){
            serverSocket = new ServerSocket(PORT);
            // 服务器从端口监听连接,监听语句
            socket = serverSocket.accept();
        } else if (isIP(str)){
            socket = new Socket(str, PORT);
        } else {
            throw new IllegalArgumentException("Parameter is wrong.");
        }
 
        // 创建新线程,用于等待接收客户端发来的消息
        (new MyTalk()).new ThreadHandleSendAClient(socket);
        // 定义输出流,发送消息
        DataOutputStream outputToClient = new DataOutputStream(
                socket.getOutputStream());
        while (true) {
                // 控制台输入反馈给客户端的信息
                String sedServer = inputData.nextLine();
                // 将输入的消息发送给客户端
                outputToClient.writeUTF(sedServer);
        }
    }
 
    public class ThreadHandleSendAClient implements Runnable {
        private Socket socket;
 
        ThreadHandleSendAClient(Socket socket) {
            this.socket = socket;
            new Thread(this).start();
        }
 
        public void run() {
            try {
                // 接收客户端发送来的消息并在控制台显示
                DataInputStream inputFromClient = new DataInputStream(
                        socket.getInputStream());
                while (true) {
                    String revClient = inputFromClient.readUTF();
                    System.out.println(revClient);
                }
            } catch (IOException ex) {
                System.out.println(ex);
            }
        }
    }
     
    private static boolean isIP(String str) {
        String num = "(25[0-5]|2[0-4]\\d|[0-1]\\d{2}|[1-9]?\\d)";
        String regex = "^" + num + "\\." + num + "\\." + num + "\\." + num + "$";
        return match(regex, str);
    }
     
    private static boolean match(String regex, String str) {
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(str);
        return matcher.matches();
        }
}

 打包为可执行jar,步骤如下:

  1.   1)在要打包的项目上右击,选择Export  2)在弹出的窗口中,选择Java -> Runnable JAR File,然后点击next按钮   3)在Runnable JAR File Specification窗口中,选择Launch configuration和Export destination  4)点击Finish按钮,打包完成。

  执行jar:cmd -> java -jar jar文件路径 参数

  在同一台机子上的运行过程:先输入cmd ->java -jar jar文件路径 wait ,启动服务器监听端口号;再输入cmd ->java -jar jar文件路径 IP地址,连接;交互式输入输出数据,接收和发送消息。

 

深深的感谢男友不揍之恩,估计再写不出来我就该挨揍了。。。