這是從另一個論壇的代碼修改的
這中間還用到了設計模式中的代理模式
public class JavaClient extends JFrame implements ActionListener//以JFrame為基類
{
JButton sendButton; //
JTextField inputField; // 輸入框
JTextArea outputArea; // 服務器返回框
static ClientAgent ca;
public JavaClient() //在建構函數中完成圖形界面的初始化
{
inputField=new JTextField(
outputArea=new JTextArea(
sendButton=new JButton(
JPanel panel=new JPanel(); //新建面板
panel
panel
panel
panel
sendButton
setTitle(
setContentPane(panel);
}
public static void main(String[] args)
{
JavaClient frame=new JavaClient();
frame
frame
ca=new ClientAgent(
}
public void actionPerformed(ActionEvent ae)
{
if(ae
{
try
{
ca
System
}catch(Exception ex)
{
ex
}
outputArea
}
}
}
import java
import
/**
* @author Administrator
*
* TODO To change the template for this generated type comment go to
* Window
*/
public class ClientAgent {
PrintStream ops; //輸出流(指向服務器)
DataInputStream ips;//輸入流(來自服務器)
BufferedReader bf;
String cltRequest;//客戶端請求
String svrResponse;//服務器端回應
public ClientAgent(String serverName
{
try
{
Socket clientSocket=new Socket(serverName
ops=new PrintStream(clientSocket
//ips=new DataInputStream(clientSocket
bf = new BufferedReader(new InputStreamReader(clientSocket
}
catch(Exception e)
{
System
}
}
public void sendRequest(String request)
{
ops
}
public String getResponse()
{
String str=new String();
try
{
//str=ips
str = bf
System
}
catch(IOException e){} //必須捕獲錯誤
return str;
}
}
import java
import
/**
* @author Administrator
*
* TODO To change the template for this generated type comment go to
* Window
*/
public class ServerAgent {
ServerSocket svrSkt=null;
Socket cltSkt=null;
//DataInputStream input=null; //輸入流
BufferedReader inf=null;
PrintStream output=null; //輸出流
public ServerAgent(int port) //main()函數傳遞監聽端口號
{
System
try
{
svrSkt=new ServerSocket(port); //開始監聽
}catch(IOException e){System
try
{
cltSkt=svrSkt
}
catch(IOException e){System
try
{
//input=new DataInputStream(cltSkt
inf = new BufferedReader(new InputStreamReader(cltSkt
output=new PrintStream(cltSkt
}
catch(IOException e){}
output
}
public String getRequest()
{
System
String frmClt=null;
try
{
//frmClt=input
frmClt = inf
System
}
catch(Exception e){
System
System
}
return frmClt;
}
public void sendResponse(String response)
{
System
try
{
output
}
catch(Exception e){
System
System
}
}
public static void main(String[] args) throws IOException
{
ServerAgent sa=new ServerAgent(
while(true)
{
sa
}
}
}
From:http://tw.wingwit.com/Article/program/Java/hx/201311/26907.html