?? client.java
字號:
import java.net.*;
import java.io.*;
import javax.swing.*;
import java.util.*;
/**
* @author yeeku.H.lee kongyeeku@163.com
* @version 1.0
* <br>Copyright (C), 2005-2008, yeeku.H.Lee
* <br>This program is protected by copyright laws.
* <br>Program Name:
* <br>Date:
*/
public class Client
{
private static final int SERVER_PORT = 30000;
private Socket socket;
private PrintStream ps;
private BufferedReader brServer;
private BufferedReader keyIn;
public void init()
{
try
{
//初始化代表鍵盤的輸入流
keyIn = new BufferedReader(
new InputStreamReader(System.in));
//連接到服務器
socket = new Socket("127.0.0.1", SERVER_PORT);
//獲取該Socket對應的輸入流和輸出流
ps = new PrintStream(socket.getOutputStream());
brServer = new BufferedReader(
new InputStreamReader(socket.getInputStream()));
String tip = "";
//采用循環不斷地彈出對話框要求輸入用戶名
while(true)
{
String userName = JOptionPane.showInputDialog(tip + "輸入用戶名");
//將用戶輸入的用戶名的前后增加協議字符串后發送
ps.println(YeekuProtocol.USER_ROUND + userName
+ YeekuProtocol.USER_ROUND);
//讀取服務器的響應
String result = brServer.readLine();
//如果用戶重復,開始下次循環
if (result.equals(YeekuProtocol.NAME_REP))
{
tip = "用戶名重復!請重新";
continue;
}
//如果服務器返回登陸成功,結束循環
if (result.equals(YeekuProtocol.LOGIN_SUCCESS))
{
break;
}
}
}
//捕捉到異常,關閉網絡資源,并退出該程序
catch (UnknownHostException ex)
{
System.out.println("找不到遠程服務器,請確定服務器已經啟動!");
closeRs();
System.exit(1);
}
catch (IOException ex)
{
System.out.println("網絡異常!請重新登陸!");
closeRs();
System.exit(1);
}
//以該Socket對應的輸入流啟動ClientThread線程
new ClientThread(brServer).start();
}
//定義一個讀取鍵盤輸出,并向網絡發送的方法
private void readAndSend()
{
try
{
//不斷讀取鍵盤輸入
String line = null;
while((line = keyIn.readLine()) != null)
{
//如果發送的信息中有冒號,且以//開頭,則認為想發送私聊信息
if (line.indexOf(":") > 0 && line.startsWith("//"))
{
line = line.substring(2);
//冒號之前的是私聊用戶,冒號之后的是聊天信息
ps.println(YeekuProtocol.PRIVATE_ROUND +
line.split(":")[0] + YeekuProtocol.SPLIT_SIGN +
line.split(":")[1] + YeekuProtocol.PRIVATE_ROUND);
}
else
{
ps.println(YeekuProtocol.MSG_ROUND + line
+ YeekuProtocol.MSG_ROUND);
}
}
}
//捕捉到異常,關閉網絡資源,并退出該程序
catch (IOException ex)
{
System.out.println("網絡通信異常!請重新登陸!");
closeRs();
System.exit(1);
}
}
//關閉Socket、輸入流、輸出流的方法
private void closeRs()
{
try
{
if (keyIn != null)
{
ps.close();
}
if (brServer != null)
{
ps.close();
}
if (ps != null)
{
ps.close();
}
if (socket != null)
{
keyIn.close();
}
}
catch (IOException ex)
{
ex.printStackTrace();
}
}
public static void main(String[] args)
{
Client client = new Client();
client.init();
client.readAndSend();
}
}
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -