?? chatclient.java
字號:
//文件名:ChatClient.java
import java.net.*;
import java.io.*;
/**
* <p>Title: 網絡聊天吧</p>
* <p>Description: 這是一個使用數據報通訊方式的聊天程序的客戶端</p>
* <p>Copyright: Copyright (c) 2003</p>
* <p>Filename: ChatClient.java</p>
* @author 杜江
* @version 1.0
*/
public class ChatClient{
private DatagramSocket s;
private InetAddress hostAddress;
private byte[] buf = new byte[1000];
private DatagramPacket dp = new DatagramPacket(buf,buf.length);
/**
*<br>方法說明:構造器,這里實現接收用戶輸入和與服務器通訊
*<br>輸入參數:
*<br>返回類型:
*/
public ChatClient(){
try{
//使用構造器,創建使用本機任何可用端口的數據包Socket
s = new DatagramSocket();
//獲取本地IP
hostAddress = InetAddress.getByName("localhost");
System.out.println("Client start............");
while(true){
String outMessage ="";
//讀取輸入
BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
try{
outMessage = stdin.readLine();
}catch(IOException ie){
System.err.println("IO error!");
}
//如果輸入“bye”則表示退出程序
if(outMessage.equals("bye")) break;
String outString = "Client say: "+ outMessage;
byte[] buf = outString.getBytes();
//打包數據,發送數據
DatagramPacket out = new DatagramPacket(buf,buf.length,hostAddress,ChatServer.PORT);
s.send(out);
//等待服務器返回
s.receive(dp);
String rcvd = "rcvd from "+ dp.getAddress() + ", " + dp.getPort() +
": "+ new String(dp.getData(),0,dp.getLength());
System.out.println(rcvd);
}
}catch(UnknownHostException e){
System.out.println("Can;t open socket");
System.exit(1);
}catch(SocketException e){
System.out.println("Can;t open socket");
e.printStackTrace();
System.exit(1);
}catch(IOException e){
System.err.println("Communication error");
e.printStackTrace();
System.exit(1);
}catch(Exception e){
System.err.println("Communication error");
e.printStackTrace();
System.exit(1);
}
System.out.println("ChatClient over");
}
/**
*<br>方法說明:主方法
*<br>輸入參數:
*<br>返回類型:
*/
public static void main(String[] args){
new ChatClient();
}
}
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -