Java Socket基礎[備忘]
1.服務端----Server.java
import javax.swing.*;
import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;
/**
* Created by JXJ on 2017/6/26.
*/
public class Server extends JFrame{
private JTextField userText;
private JTextArea chatWindow;
private ObjectOutputStream output;
private ObjectInputStream input;
private ServerSocket server;
private Socket connection;
//構(gòu)造方法
public Server(){
super("即時聊天小程序");
userText=new JTextField();
userText.setEditable(false);
userText.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
sendMessage(e.getActionCommand());
userText.setText("");
}
});
add(userText,BorderLayout.NORTH);
chatWindow=new JTextArea();
add(new JScrollPane(chatWindow));
setSize(300,150);
setVisible(true);
}
//建立并啟動服務
public void startRununing(){
try{
server=new ServerSocket(6789,100);
while(true){
try{
//等待連接
waitForConnect();
//獲取輸入輸出數(shù)據(jù)流
setupStreams();
//聊天
whileChatting();
}catch (EOFException eofException){
showMessage("\n 連接已經(jīng)結(jié)束!");
}finally {
closeCrap();
}
}
}catch (IOException ioException){
ioException.printStackTrace();
}
}
//等待連接,然后顯示連接信息
private void waitForConnect() throws IOException{
showMessage(" 等待客戶端連接...\n");
connection=server.accept();
showMessage("客戶端"+connection.getInetAddress().getHostName()+"已連接!\n ");
}
//獲取輸入輸出流
private void setupStreams() throws IOException{
output=new ObjectOutputStream(connection.getOutputStream());
//這個重點關(guān)注一下
output.flush();
input=new ObjectInputStream(connection.getInputStream());
showMessage("\n數(shù)據(jù)流已建立!\n ");
}
//聊天信息處理
private void whileChatting() throws IOException {
String message="現(xiàn)在你已經(jīng)連接上了!";
sendMessage(message);
ableToType(true);
do{
try{
message=(String)input.readObject();
showMessage(message+"\n ");
}catch (ClassNotFoundException classNotFoundException){
showMessage("用戶發(fā)送信息轉(zhuǎn)換異常!\n");
}
}while(!message.equals("client-end"));
}
//聊天結(jié)束后關(guān)閉輸入輸出流和socket
private void closeCrap() {
showMessage("正在關(guān)閉連接...\n");
ableToType(false);
try{
//注意關(guān)閉先后順序 輸出流 輸入流 socket
output.close();
input.close();
connection.close();
}catch (IOException ioException){
}
}
//給客戶端發(fā)送信息
private void sendMessage(String message) {
try{
output.writeObject("Server"+message);
output.flush();
showMessage("Server"+message+"\n");
}catch (IOException ioException){
chatWindow.append("[錯誤] 我沒有成功發(fā)送信息!");
}
}
//在窗口上實時顯示聊天信息
private void showMessage(final String text) {
//注意窗口更新信息的方式
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
chatWindow.append(text);
}
});
}
//讓用戶輸入信息
private void ableToType(final boolean tof) {
//注意按鈕的禁用與啟用的方式
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
userText.setEditable(tof);
}
});
}
}
2.服務端測試----ServerTest.java
/**
* Created by JXJ on 2017/6/26.
*/
import javax.swing.JFrame;
public class ServerTest {
public static void main(String[] args){
Server server=new Server();
server.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
server.startRununing();
}
}
3.客戶端----Client.java
/**
* Created by JXJ on 2017/6/26.
*/
import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Client extends JFrame {
private JTextField userText;
private JTextArea chatwindow;
private ObjectInputStream input;
private ObjectOutputStream output;
private String message="";
private String serverIP;
private Socket connection;
//構(gòu)造方法
public Client(String host){
super("客戶端");
serverIP=host;
userText=new JTextField();
userText.setEditable(false);
userText.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
sendMessage(e.getActionCommand());
userText.setText("");
}
});
add(userText,BorderLayout.NORTH);
chatwindow=new JTextArea();
add(new JScrollPane(chatwindow),BorderLayout.CENTER);
setSize(300,150);
setVisible(true);
}
//建立連接
public void startRununing(){
try{
connectToServer();
setupStreams();
whileChatting();
}catch (EOFException eofException){
showMessage("客戶端斷開連接! \n");
}catch (IOException ioExceptiopn){
ioExceptiopn.printStackTrace();
}
finally {
closeCrap();
}
}
//連接到服務端
private void connectToServer() throws IOException {
showMessage("正在嘗試連接服務端... \n");
connection=new Socket(InetAddress.getByName(serverIP),6789);
showMessage("已連接至"+connection.getInetAddress().getHostName());
}
//建立輸入輸出流
private void setupStreams() throws IOException {
output=new ObjectOutputStream(connection.getOutputStream());
output.flush();
input=new ObjectInputStream(connection.getInputStream());
showMessage("已創(chuàng)建輸入輸出流... \n");
}
//聊天信息處理
private void whileChatting() throws IOException {
ableToType(true);
do{
try{
message=(String)input.readObject();
showMessage(message+"\n");
}catch (ClassNotFoundException classNotFoundException){
showMessage(" 未知的輸入對象類型\n");
}
}while(!message.equals("server-end"));
}
//關(guān)閉輸入輸出流和socket
private void closeCrap() {
showMessage("關(guān)閉客戶端連接資源\n");
ableToType(false);
try{
output.close();
input.close();
connection.close();
}catch (IOException ioException){
ioException.printStackTrace();
}
}
//給服務端發(fā)送信息
private void sendMessage(String message) {
try{
output.writeObject("client-"+message);
output.flush();
showMessage("client-"+message+"\n");
}catch (IOException ioException){
showMessage("客戶端發(fā)送數(shù)據(jù)失敗\n");
}
}
//在窗口上實時顯示聊天信息
private void showMessage(final String text) {
//注意窗口更新信息的方式
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
chatwindow.append(text);
}
});
}
//讓用戶輸入信息
private void ableToType(final boolean tof) {
//注意按鈕的禁用與啟用的方式
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
userText.setEditable(tof);
}
});
}
}
4.客戶端測試----ClientTest.java
import javax.swing.*;
/**
* Created by JXJ on 2017/6/26.
*/
public class ClientTest {
public static void main(String[] args){
Client client=new Client("127.0.0.1");
client.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
client.startRununing();
}
}
【路漫漫其修遠兮,吾將上下而求索】
posted on 2017-06-29 21:24 binghuojxj 閱讀(217) 評論(0) 收藏 舉報
浙公網(wǎng)安備 33010602011771號