ServerSocket服务器通信

来源:互联网 发布:网络歌手音频资料 编辑:程序博客网 时间:2024/05/24 01:38

程序运行后,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();}}



0 0
原创粉丝点击