先啓動服務端,再啓動客戶端
client
package learn.io;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
public class ClientDemo {
public static void main(String[] args) throws IOException {
System.out.println("客戶端啓動");
Socket client = new Socket();
client.connect(new InetSocketAddress("localhost", 9999));
OutputStream ou = client.getOutputStream();
ou.write("這是客戶端發來的消息".getBytes());
// flush() 則要求立即將緩衝區的數據輸出到接收方
ou.flush();
Thread inThread = new Thread() {
@Override
public void run() {
int itemp;
byte[] rbyte = new byte[1024];
while (true) {
try {
InputStream in = client.getInputStream();
if (in != null) {
itemp = in.read(rbyte);
System.out.println("讀取服務端消息大小: " + itemp);
if (itemp > 0) {
System.out.println("服務端傳過來的消息: " + new String(rbyte));
// 接收一次服務端信息就退出
if (client != null) {
if (in != null) {
in.close();
}
if (ou != null) {
ou.close();
}
client.close();
return;
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
};
inThread.start();
// 給服務端發送消息
}
}
server
package learn.io;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashSet;
import java.util.Set;
/*
* 舊io socket編程
* 注意: 不關閉socket就不關閉socket的流
*/
public class ServerDemo {
public static Set<Socket> clients = new HashSet<Socket>();
public static boolean close = true;
public static int count = 1;
public static void main(String[] args) throws IOException {
System.out.println("服務端啓動");
ServerSocket server = new ServerSocket();
server.bind(new InetSocketAddress("localhost", 9999));
// 等待客戶端連接
while (close) {
Socket client = server.accept();
System.out.println(count + "個客戶端連接成功");
count++;
clients.add(client);
InputStream in = client.getInputStream();
byte[] rbyte = new byte[1024];
// 創建匿名線程
Thread thread = new Thread() {
int itemp = 0;
@Override
public void run() {
try {
itemp = in.read(rbyte);
System.out.println("讀取客戶端消息大小: " + itemp);
if (itemp > 0) {
System.out.println("客戶端消息: " + new String(rbyte));
// 將連接上來的客戶端信息轉發給其他客戶端
for (Socket c : clients) {
if (!client.equals(c)) {
boolean btemp = c.isClosed();
System.out.println("當前連接是否以關閉: " + btemp);
btemp = c.isConnected();
System.out.println("當前連接是否成功: " + btemp);
if (!c.isClosed() && c.isConnected()) {
try {
// 發送前驗證該連接是否有效
OutputStream ou = c.getOutputStream();
ou.write((client.getInetAddress().toString() + "連接上服務端").getBytes());
// flush() 則要求立即將緩衝區的數據輸出到接收方
ou.flush();
} catch (IOException e1) {
System.out.println("關閉無效連接");
c.close();
}
}
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
};
thread.start();
}
System.out.println("服務端退出");
}
}