2010年1月20日 星期三

Java Socket

Server:

public class myServer {
public static final String SERVERIP = "127.0.0.1";
public static final int SERVERPORT = 13267;
public static void main(String args[]) {
ServerSocket server;
Socket socket;
String s;
InputStream Is;
OutputStream Os;
DataInputStream DIS;
PrintStream PS;

try {
// 在端口4321注冊服務
server = new ServerSocket(SERVERPORT);
socket = server.accept(); // 監聽窗口,等待連接

System.out.println("server ok");
System.out
.println("************************************************");
System.out.println("");

// 獲得對應Socket的輸入/輸出流
Is = socket.getInputStream();
Os = socket.getOutputStream();
// 建立數據流
DIS = new DataInputStream(Is);
PS = new PrintStream(Os);
DataInputStream in = new DataInputStream(System.in);
while (true) {
System.out.println("");
System.out.println("please wait client's message...");
System.out.println("");
s = DIS.readLine(); // 讀入從client傳來的字符串
System.out.println("client said:" + s); // 打印字符串
if (s.trim().equals("BYE"))
break; // 如果是"BYE",就退出
System.out.print("you say:");
s = in.readLine(); // 讀取用戶輸入的字符串
PS.println(s); // 將讀取得字符串傳給client
if (s.trim().equals("BYE"))
break; // 如果是"BYE",就退出

}

// 關閉連接
DIS.close(); // 關閉數據輸入流
PS.close(); // 關閉數據輸出流
Is.close(); // 關閉輸入流
Os.close(); // 關閉輸出流
socket.close(); // 關閉sockey
} catch (Exception e) {
System.out.println("Error:" + e);
}
}
}

Client:

public class myClient{
public static final String SERVERIP = "127.0.0.1";
public static final int SERVERPORT = 13267;
public static void main(String args[]) {
Socket socket;
String s = "yxfsoft@263.net";
String len;
InputStream Is;
OutputStream Os;
DataInputStream DIS;
PrintStream PS;
try {
socket = new Socket(SERVERIP, SERVERPORT);
System.out.println("client ok");
System.out
.println("************************************************");
System.out.println("");
// 獲得對應socket的輸入/輸出流
Is = socket.getInputStream();
Os = socket.getOutputStream();
// 建立數據流
DIS = new DataInputStream(Is);
PS = new PrintStream(Os);
DataInputStream in = new DataInputStream(System.in);
while (true) {
System.out.print("you say:");
s = in.readLine(); // 讀取用戶輸入的字符串
PS.println(s); // 將讀取得字符串傳給server
if (s.trim().equals("BYE"))
break; // 如果是"BYE",就退出
else {
System.out.println("");
System.out.println("please wait server's message...");
System.out.println("");
}
s = DIS.readLine(); // 從服務器獲得字符串
System.out.println("server said:" + s); // 打印字符串
if (s.trim().equals("BYE"))
break; // 如果是"BYE",就退出

}
// 關閉連接
DIS.close(); // 關閉數據輸入流
PS.close(); // 關閉數據輸出流
Is.close(); // 關閉輸入流
Os.close(); // 關閉輸出流
socket.close(); // 關閉socket
} catch (Exception e) {
System.out.println("Error:" + e);
}
}
}

沒有留言:

張貼留言