1.main方法:
package peixun;
public class MyServerSocket {
public static void main(String[] args) {
new ServerListener().start();
}
}
2.建立连接
package peixun;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import javax.swing.JOptionPane;
public class ServerListener extends Thread {
@Override
public void run() {
try {
//()内写的是监听的端口,可以是1-65535
ServerSocket serverSocket = new ServerSocket(12345);
while (true) {
//侦听客户端的连接,会阻塞当前的线程
Socket socket = serverSocket.accept();//此时已经监听12345这个端口了
//建立连接
JOptionPane.showMessageDialog(null, "有客户端链接到了本机的12345端口");
//因为要与多个客户端交互,所以要将socket传递给新的线程,接下来就是创建与socket通信的线程
new ChatSocket(socket).start();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
3.进行socket通信
package peixun;
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;
}
public void out(String out) {
try {
socket.getOutputStream().write(out.getBytes("UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void run() {
int count = 0;
while (true) {
count++;
out("loop"+count);
try {
sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}