程序运行后,cmd窗口中运行:telnet localhost 12345
ServerListener.java
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import javax.swing.JOptionPane;
public class ServerListener extends Thread {
public void run() {
try {
ServerSocket serverSocket = new ServerSocket(12345);
Socket socket = serverSocket.accept();
JOptionPane.showMessageDialog(null, "有客户段链接到本机12345端口");
new ChatSocket(socket).start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
ChatSocket.java
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.Socket;
public class ChatSocket extends Thread {
Socket socket;
public ChatSocket(Socket s) {
this.socket = s;
}
private void out(String out) {
try {
socket.getOutputStream().write(out.getBytes("UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public void run() {
int count = 0;
while (true) {
count++;
out("loop:" + count);
try {
sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
MyServerSocket.java
public class MyServerSocket {
public static void main(String[] args) {
new ServerListener().start();
}
}