資源簡介
簡單多客戶端聊天GUI界面,服務器轉發消息,適用于課程作業

代碼片段和文件信息
import?java.awt.BorderLayout;
import?java.awt.Button;
import?java.awt.Container;
import?java.awt.FlowLayout;
import?java.awt.event.ActionEvent;
import?java.awt.event.ActionListener;
import?java.io.*;
import?java.net.ServerSocket;
import?java.net.Socket;
import?java.util.ArrayList;
import?java.util.List;
import?java.util.Scanner;
import?javax.swing.Jframe;
import?javax.swing.JOptionPane;
import?javax.swing.JPanel;
import?javax.swing.JTextArea;
import?javax.swing.JTextField;
public?class?Client?{
public?static?int?i=0;//想聊天的線程號
public?static?void?main(String[]?args)?throws?ClassNotFoundException?{
try?{
Socket client=new?Socket(“localhost“8888);//本地ip創建socket
BufferedReader?br=new?BufferedReader(new?InputStreamReader(client.getInputStream()));//緩沖輸入流讀取當前的線程號
? int?n=Integer.parseInt(br.readLine());
? SwingTest?swingtest=new?SwingTest();//實例化一個面板對象
?
?
? swingtest.jt2.setText(“當前線程號為“+n+“???請先在上方輸入你想聊天的線程號?\n“);//把這條消息送到當前文本版框中
? System.out.println(“當前線程號為“+n+“???請先在上方輸入你想聊天的線程號?\n“);
?
?
? ?receiveMessage?re=new?receiveMessage(clientswingtest);?//這個線程用來一直從服務器接收消息
? ?re.start(); //因為存在一個while的讀寫操作,所以必須開啟線程操作
?
?PrintWriter?pr=new?PrintWriter(client.getOutputStream());//輸出流
?System.out.println(“再在下方輸入聊天內容,exit結束“);
//輸出流,發消息給服務器中轉
?
?swingtest.jt2.append(“再在下方輸入聊天內容,exit結束\n\n“);//文本2中,追加提示
?
?
?swingtest.b1.addActionListener(new?ActionListener()?{ //問題
public?void?actionPerformed(ActionEvent?e)?{
try?{
String?str1=swingtest.jt1.getText().toString();
?pr.println(str1);
pr.flush();
swingtest.jt2.append(“你想要與?“+str1+“號客戶端交流\n“);
}catch?(Exception?e1)?{
//?TODO:?handle?exception
}
}
});
?
?swingtest.b3.addActionListener(new?ActionListener(){
public?void?actionPerformed(ActionEvent?e2)?{
?try?{
String?str3=swingtest.jt3.getText().toString();
pr.println(“線程“+n+“:“+str3);
pr.flush();
swingtest.jt2.append(“線程“+n+“:??“+str3+“\n“);
swingtest.jt3.setText(““);
?}catch?(Exception?e3)?{
//?TODO:?handle?exception
}
}
});
}?catch?(IOException?e)?{}
}
}
class?SwingTest?extends?Jframe?{
Jframe?jf=null;
Container?container=null;
JPanel?jp1jp2jp3;
JTextField?jt1jt3;
JTextArea?jt2;
Button?b1b3;
public?SwingTest()
{
jf=new?Jframe(“即時通信“);
container=jf.getContentPane();
container.setLayout(new?BorderLayout());//設置為邊界布局管理器
?jp1=new?JPanel(new?FlowLayout(155));//居中對齊,組件間間隔5
?jp2=new?JPanel(new?FlowLayout(155));//居中對齊,組件間間隔5
jp3=new?JPanel(new?FlowLayout(155));//居中對齊,組件間間隔5
?jt1=new?JTextField(22);//輸入連接線程號的文本,放在上邊,這里的參數表示這個輸入框的長度為10列。
?jt2=new?JTextArea(2227);//展示來往消息的文
?屬性????????????大小?????日期????時間???名稱
-----------?---------??----------?-----??----
?????文件????????1006??2018-05-06?11:41??ClientThread.java
?????文件????????1289??2018-05-04?18:50??Server.java
?????文件?????????761??2018-05-04?18:50??receiveMessage.java
?????文件????????1081??2018-05-04?16:44??user.java
?????文件????????3756??2018-05-06?11:46??Client.java
評論
共有 條評論