该程序演示了用 Java Socket 通讯和多线程的编程技术。
1.编译 javac socketTest.java
2.运行 java socketTest <主机> <端口>
3.说明
程序首先与指定的主机和端口建立联系,然后创建一个线程,收听来自
该主机的信息。程序接受键盘输入,并发送到主机和端口。例如,
- 与 smtp 服务器的通讯
C:/test/java>java socketTest smtp.263.net 25
Try to talk with: smtp.263.net at: 25
Establishing connection ...
Connection OK.
Start Listener ...
Ready to accept input ...
220 smtp.263.net ESMTP
HELO smtp.263.net ***
250 smtp.263.net
MAIL FROM:yysun@263.net ***
250 Ok
RCPT TO:yysun@263.net ***
250 Ok
DATA ***
354 End data with <CR><LF>.<CR><LF>
Subject: Hi ***
This is a test message manually generated. ***
.
250 Ok: queued as B44D91C4D1479
QUIT ***
221 Bye
- 与 pop3 服务器的通讯
C:/test/java>java socketTest 263.net 110
Try to talk with: 263.net at: 110
Establishing connection ...
Connection OK.
Start Listener ...
Ready to accept input ...
+OK incore system mail POP3 Server ready
USER yysun ***
+OK core mail
PASS xxxxxx ***
+OK 2 message(s) [6327 byte(s)]
STAT ***
+OK 2 6327
UIDL ***
+OK core mail
1 MX7v3pB1ER457_EEDE9a
2 MX8SN_v06c367ohDDEOv
.
QUIT ***
+OK core mail
***为键盘输入的内容
同理。还可以与其他许多服务器通讯。
源程序如下:
import java.io.*;
import java.net.*;
class socketListener implements Runnable {
private Socket client;
socketListener (Socket client) {
this.client = client;
}
public void run(){
String line;
try {
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
while(true) {
line = in.readLine();
if (line!=null) System.out.println(line);
}
}
catch (IOException e) {
System.out.println("e.getMessage()");
System.exit(-1);
}
}
}
public class socketTest {
public void test(String host, int port) {
String ss;
try{
System.out.println("Establishing connection ...");
Socket socket = new Socket(host, port);
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader kbd = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Connection OK.");
System.out.println("Start Listener ...");
socketListener sl = new socketListener(socket);
Thread t = new Thread(sl);
t.start();
System.out.println("Ready to accept input ...");
while (true) {
ss = kbd.readLine();
out.println(ss);
}
}
catch (IOException e) {
System.out.println(e.getMessage());
System.exit(-1);
}
}
public static void main(String[] args){
if (args.length < 2) {
System.out.println("Usage: java socketTest <Host> <Port>");
System.exit(-1);
}
String host = args[0];
int port = Integer.parseInt(args[1], 10);
System.out.println("Try to talk with: " + host + " at: " + port);
socketTest test = new socketTest();
test.test(host, port);
}
}