TCPServer.java
import java.net.*;
import java.io.*;
public class TCPServer {
public static void main(String[] args) throws Exception {
ServerSocket ss = new ServerSocket(6666);//時刻監聽,等//待client(客戶端)連接,6666是端口號
while(true) {
Socket s = ss.accept();//Socket是client端的連//接,插座用于接收 accept()
System.out.println("a client connect!");
DataInputStream dis = new DataInputStream(s.getInputStream());
System.out.println(dis.readUTF());//從流 in 中讀取用 UTF-8 修改版格式編碼的 Unicode 字符格式的字符串
dis.close();
s.close();
}
}
}
TCPClient.java
import java.net.*;
import java.io.*;
public class TCPClient {
public static void main(String[] args) throws Exception {
Socket s = new Socket("127.0.0.1", 6666);//插座 用于連接//server服務端,127.0.0.1本機ip, 6666端口號
OutputStream os = s.getOutputStream();//通過輸出管道說話
DataOutputStream dos = new DataOutputStream(os);//包裝輸出管道,應用程序以適當方式將基本 Java 數據類型寫入輸出流
//或者InputStream is = ss.getInputStream();
DataInputStream dis = new DataInputStream(is);
Thread.sleep(30000);// 線程狀態
dos.writeUTF("hello server!");//writeUTF()將表示長度信息的兩個字節寫入輸出流
dos.flush();//刷新此 Image 對象正在使用的所有資源
dos.close();
s.close();
}
}
posted on 2009-04-30 09:35
鵬凌 閱讀(112)
評論(0) 編輯 收藏