概述
專注于為中小企業(yè)提供網(wǎng)站建設(shè)、網(wǎng)站制作服務(wù),電腦端+手機端+微信端的三站合一,更高效的管理,為中小企業(yè)平原免費做網(wǎng)站提供優(yōu)質(zhì)的服務(wù)。我們立足成都,凝聚了一批互聯(lián)網(wǎng)行業(yè)人才,有力地推動了千余家企業(yè)的穩(wěn)健成長,幫助中小企業(yè)通過網(wǎng)站建設(shè)實現(xiàn)規(guī)模擴充和轉(zhuǎn)變。
具體框架使用jframe,文本框組件:JTextField;密碼框組件:JPasswordField;標簽組件:JLabel;復(fù)選框組件:JCheckBox;單選框組件:JRadioButton;按鈕組件JButton。
登錄界面:
代碼實例
import javax.swing.*;
import java.awt.*; ? //導(dǎo)入必要的包
public class denglu extends JFrame{
JTextField jTextField ;//定義文本框組件
JPasswordField jPasswordField;//定義密碼框組件
JLabel jLabel1,jLabel2;
JPanel jp1,jp2,jp3;
JButton jb1,jb2; //創(chuàng)建按鈕
public denglu(){
jTextField = new JTextField(12);
jPasswordField = new JPasswordField(13);
jLabel1 = new JLabel("用戶名");
jLabel2 = new JLabel("密碼");
jb1 = new JButton("確認");
jb2 = new JButton("取消");
jp1 = new JPanel();
jp2 = new JPanel();
jp3 = new JPanel();
//設(shè)置布局
this.setLayout(new GridLayout(3,1));
jp1.add(jLabel1);
jp1.add(jTextField);//第一塊面板添加用戶名和文本框
jp2.add(jLabel2);
jp2.add(jPasswordField);//第二塊面板添加密碼和密碼輸入框
jp3.add(jb1);
jp3.add(jb2); //第三塊面板添加確認和取消
// ? ? ? ?jp3.setLayout(new FlowLayout()); ?//因為JPanel默認布局方式為FlowLayout,所以可以注銷這段代碼.
this.add(jp1);
this.add(jp2);
this.add(jp3); ?//將三塊面板添加到登陸框上面
//設(shè)置顯示
this.setSize(300, 200);
//this.pack();
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
this.setTitle("登陸");
}
public static void main(String[] args){
new denglu();
}
}
拓展內(nèi)容
java swing包
Swing 是一個為Java設(shè)計的GUI工具包。
Swing是JAVA基礎(chǔ)類的一部分。
Swing包括了圖形用戶界面(GUI)器件如:文本框,按鈕,分隔窗格和表。
Swing提供許多比AWT更好的屏幕顯示元素。它們用純Java寫成,所以同Java本身一樣可以跨平臺運行,這一點不像AWT。它們是JFC的一部分。它們支持可更換的面板和主題(各種操作系統(tǒng)默認的特有主題),然而不是真的使用原生平臺提供的設(shè)備,而是僅僅在表面上模仿它們。這意味著你可以在任意平臺上使用JAVA支持的任意面板。輕量級組件的缺點則是執(zhí)行速度較慢,優(yōu)點就是可以在所有平臺上采用統(tǒng)一的行為。
概念解析:
JFrame?– java的GUI程序的基本思路是以JFrame為基礎(chǔ),它是屏幕上window的對象,能夠最大化、最小化、關(guān)閉。
JPanel?– Java圖形用戶界面(GUI)工具包swing中的面板容器類,包含在javax.swing 包中,可以進行嵌套,功能是對窗體中具有相同邏輯功能的組件進行組合,是一種輕量級容器,可以加入到JFrame窗體中。。
JLabel?– JLabel 對象可以顯示文本、圖像或同時顯示二者??梢酝ㄟ^設(shè)置垂直和水平對齊方式,指定標簽顯示區(qū)中標簽內(nèi)容在何處對齊。默認情況下,標簽在其顯示區(qū)內(nèi)垂直居中對齊。默認情況下,只顯示文本的標簽是開始邊對齊;而只顯示圖像的標簽則水平居中對齊。
JTextField?–一個輕量級組件,它允許編輯單行文本。
JPasswordField?– 允許我們輸入了一行字像輸入框,但隱藏星號(*) 或點創(chuàng)建密碼(密碼)
JButton?– JButton 類的實例。用于創(chuàng)建按鈕類似實例中的 "Login"。
給你一個聊天室的,這個是客戶端之間的通信,服務(wù)器負責(zé)接收和轉(zhuǎn)發(fā),你所要的服務(wù)器與客戶端對發(fā),只要給服務(wù)器寫個界面顯示和輸入就行,所有代碼如下:
你測試的時候應(yīng)該把所有代碼放在同一個工程下,因為客戶端可服務(wù)器共用同一個POJO,里面有些包的錯誤,刪除掉就行了
服務(wù)器代碼,即服務(wù)器入口程序:
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectOutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Date;
import java.util.HashSet;
public class ChatRoomServer {
private ServerSocket ss;
private HashSetSocket allSockets;
private UserDao dao;
public ChatRoomServer(){
try {
ss=new ServerSocket(9999);
allSockets=new HashSetSocket();
dao=new UserDaoForTextFile(new File("d:/stu/user.txt"));
} catch (IOException e) {
e.printStackTrace();
}
}
public void startService() throws IOException{
while(true){
Socket s=ss.accept();
allSockets.add(s);
new ChatRoomServerThread(s).start();
}
}
class ChatRoomServerThread extends Thread{
private Socket s;
public ChatRoomServerThread(Socket s){
this.s=s;
}
public void run(){
//1,得到Socket的輸入流,并包裝。
//2,循環(huán)從輸入流中讀取一行數(shù)據(jù)。
//3,每讀到一行數(shù)據(jù),判斷該行是否是退出命令?
//4,如果是退出命令,則將當前socket從集合中刪除,關(guān)閉當前socket,并跳出循環(huán)
//5,如果不是退出命令,則將該消model.getCurrentUser().getName()息轉(zhuǎn)發(fā)給所有在線的客戶端。
// 循環(huán)遍歷allSockets集合,得到每一個socket的輸出流,向流中寫出該消息。
BufferedReader br=null;
String str = null;
try {
br = new BufferedReader(new InputStreamReader(s
.getInputStream()));
while((str=br.readLine())!=null ){
if(str.indexOf("%EXIT%")==0){
allSockets.remove(s);
//向其他客戶端發(fā)送XXX退出的消息
sendMessageToAllClient(str.split(":")[1]+"離開聊天室!");
s.close();
break;
}else if(str.indexOf("%LOGIN%")==0){
String userName=str.split(":")[1];
String password=str.split(":")[2];
User user=dao.getUser(userName, password);
ObjectOutputStream oos=new ObjectOutputStream(s.getOutputStream());
oos.writeObject(user);
oos.flush();
if(user!=null){
sendMessageToAllClient(user.getName()+"進入聊天室!");
}
str = null;
}
if(str!=null){
sendMessageToAllClient(str);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void sendMessageToAllClient(String message)throws IOException{
Date date=new Date();
System.out.println(s.getInetAddress()+":"+message+"\t["+date+"]");
for(Socket temps:allSockets){
PrintWriter pw=new PrintWriter(temps.getOutputStream());
pw.println(message+"\t["+date+"]");
pw.flush();
}
}
}
public static void main(String[] args) {
try {
new ChatRoomServer().startService();
} catch (IOException e) {
e.printStackTrace();
}
}
}
客戶端代碼:
總共4個:
1:入口程序:
public class ChatRoomClient {
private ClientModel model;
public ChatRoomClient(){
// String hostName = JOptionPane.showInputDialog(null,
// "請輸入服務(wù)器主機名:");
// String portName = JOptionPane
// .showInputDialog(null, "請輸入端口號:");
//固定服務(wù)端IP和端口
model=new ClientModel("127.0.0.1",Integer.parseInt("9999"));
model.createSocket();
new LoginFrame(model).showMe();
}
public static void main(String[] args) {
new ChatRoomClient();
}
}
2:登陸后顯示界面:
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class ClientMainFrame extends JFrame{
private JTextArea area;
private JTextField field;
private JLabel label;
private JButton button;
private ClientModel model;
public ClientMainFrame(){
super("聊天室客戶端v1.0");
area=new JTextArea(20,40);
field=new JTextField(25);
button=new JButton("發(fā)送");
label=new JLabel();
JScrollPane jsp=new JScrollPane(area);
this.add(jsp,BorderLayout.CENTER);
JPanel panel=new JPanel();
panel.add(label);
panel.add(field);
panel.add(button);
this.add(panel,BorderLayout.SOUTH);
addEventHandler();
}
public ClientMainFrame(ClientModel model){
this();
this.model=model;
label.setText(model.getCurrentUser().getName());
}
public void addEventHandler(){
ActionListener lis=new SendEventListener();
button.addActionListener(lis);
field.addActionListener(lis);
this.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent arg0) {
int op=JOptionPane.showConfirmDialog(null,"確認退出聊天室嗎?","確認退出",JOptionPane.YES_NO_OPTION);
if(op==JOptionPane.YES_OPTION){
PrintWriter pw = model.getOutputStream();
if(model.getCurrentUser().getName()!=null){
pw.println("%EXIT%:"+model.getCurrentUser().getName());
pw.flush();
}
try {
Thread.sleep(200);
} catch (Exception e) {
}
System.exit(0);
}
}
});
}
public void showMe(){
this.pack();
this.setVisible(true);
this.setLocation(300,300);
this.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
new ReadMessageThread().start();
}
class SendEventListener implements ActionListener{
public void actionPerformed(ActionEvent e) {
String str=field.getText().trim();
if(str.equals("")){
JOptionPane.showMessageDialog(null, "不能發(fā)送空消息!");
return;
}
PrintWriter pw = model.getOutputStream();
pw.println(model.getCurrentUser().getName()+":"+str);
pw.flush();
field.setText("");
}
}
class ReadMessageThread extends Thread{
public void run(){
while(true){
try {
BufferedReader br = model.getInputStream();
String str=br.readLine();
area.append(str+"\n");
} catch (IOException e) {
}
}
}
}
}
3:登陸界面:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.PrintWriter;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
public class LoginFrame extends JFrame {
private static final long serialVersionUID = 1L;
private JPanel jContentPane = null;
private JLabel lab1 = null;
private JLabel lab2 = null;
private JLabel lab3 = null;
private JTextField userNameField = null;
private JPasswordField passwordField = null;
private JButton loginButton = null;
private JButton registerButton = null;
private JButton cancelButton = null;
private ClientModel model = null;
/**
* This method initializes userNameField
*
* @return javax.swing.JTextField
*/
private JTextField getUserNameField() {
if (userNameField == null) {
userNameField = new JTextField();
userNameField.setSize(new Dimension(171, 33));
userNameField.setFont(new Font("Dialog", Font.PLAIN, 18));
userNameField.setLocation(new Point(140, 70));
}
return userNameField;
}
/**
* This method initializes passwordField
*
* @return javax.swing.JPasswordField
*/
private JPasswordField getPasswordField() {
if (passwordField == null) {
passwordField = new JPasswordField();
passwordField.setSize(new Dimension(173, 30));
passwordField.setFont(new Font("Dialog", Font.PLAIN, 18));
passwordField.setLocation(new Point(140, 110));
}
return passwordField;
}
/**
* This method initializes loginButton
*
* @return javax.swing.JButton
*/
private JButton getLoginButton() {
if (loginButton == null) {
loginButton = new JButton();
loginButton.setLocation(new Point(25, 180));
loginButton.setText("登錄");
loginButton.setSize(new Dimension(75, 30));
}
return loginButton;
}
/**
* This method initializes cancelButton
*
* @return javax.swing.JButton
*/
private JButton getCancelButton() {
if (cancelButton == null) {
cancelButton = new JButton();
cancelButton.setLocation(new Point(270, 180));
cancelButton.setText("取消");
cancelButton.setSize(new Dimension(75, 30));
}
return cancelButton;
}
/**
* 顯示界面的方法,在該方法中調(diào)用addEventHandler()方法給組件添加事件監(jiān)聽器
*
*/
public void showMe(){
this.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
this.setVisible(true);
this.setLocation(300,200);
addEventHandler();
}
/**
* 該方法用于給組件添加事件監(jiān)聽
*
*/
public void addEventHandler(){
ActionListener loginListener=new LoginEventListener();
loginButton.addActionListener(loginListener);
passwordField.addActionListener(loginListener);
cancelButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
try {
model.getSocket().close();
} catch (IOException e1) {
e1.printStackTrace();
}
System.exit(0);
}
});
this.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent arg0) {
try {
model.getSocket().close();
} catch (IOException e1) {
e1.printStackTrace();
}
System.exit(0);
}
});
}
/**
* 該內(nèi)部類用來監(jiān)聽登錄事件
* @author Administrator
*
*/
class LoginEventListener implements ActionListener{
public void actionPerformed(ActionEvent e) {
//?????登錄的代碼
//1,判斷用戶名和密碼是否為空
//2,從clientmodel得到輸出流,PrintWriter
//3,發(fā)送登錄請求給服務(wù)器
//pw.println("%LOGIN%:userName:password");
//4,從socket得到對象輸入流,從流中讀取一個對象。
//5,如果讀到的對象為null,則顯示登錄失敗的消息。
//6,如果讀到的對象不為空,則轉(zhuǎn)成User對象,并且將
// clientModel的currentUser對象設(shè)置為該對象。
//7,并銷毀當前窗口,打開主界面窗口。
String userName = userNameField.getText();
char[] c = passwordField.getPassword();
String password = String.valueOf(c);
if(userName == null || userName.equals("")){
JOptionPane.showMessageDialog(null,"用戶名不能為空");
return;
}
if(password == null || password.equals("")){
JOptionPane.showMessageDialog(null,"密碼名不能為空");
return;
}
PrintWriter pw = model.getOutputStream();
pw.println("%LOGIN%:"+userName+":"+password);
pw.flush();
try {
InputStream is = model.getSocket().getInputStream();
System.out.println("is"+is.getClass());
ObjectInputStream ois = new ObjectInputStream(is);
Object obj = ois.readObject();
if(obj != null){
User user = (User)obj;
if(user != null){
model.setCurrentUser(user);
LoginFrame.this.dispose();
new ClientMainFrame(model).showMe();
}
}
else{
JOptionPane.showMessageDialog(null,"用戶名或密碼錯誤,請重新輸入");
userNameField.setText("");
passwordField.setText("");
return;
}
} catch (Exception e1) {
e1.printStackTrace();
}
}
}
public static void main(String[] args) {
new LoginFrame().showMe();
}
/**
* This is the default constructor
*/
public LoginFrame(ClientModel model) {
this();
this.model=model;
}
public LoginFrame(){
super();
initialize();
}
public ClientModel getModel() {
return model;
}
public void setModel(ClientModel model) {
this.model = model;
}
/**
* This method initializes this
*
* @return void
*/
private void initialize() {
this.setSize(362, 267);
this.setContentPane(getJContentPane());
this.setTitle("達內(nèi)聊天室--用戶登錄");
}
/**
* This method initializes jContentPane
*
* @return javax.swing.JPanel
*/
private JPanel getJContentPane() {
if (jContentPane == null) {
lab3 = new JLabel();
lab3.setText("密 碼:");
lab3.setSize(new Dimension(80, 30));
lab3.setFont(new Font("Dialog", Font.BOLD, 18));
lab3.setLocation(new Point(50, 110));
lab2 = new JLabel();
lab2.setText("用戶名:");
lab2.setSize(new Dimension(80, 30));
lab2.setToolTipText("");
lab2.setFont(new Font("Dialog", Font.BOLD, 18));
lab2.setLocation(new Point(50, 70));
lab1 = new JLabel();
lab1.setBounds(new Rectangle(54, 12, 245, 43));
lab1.setFont(new Font("Dialog", Font.BOLD, 24));
lab1.setForeground(new Color(0, 0, 204));
lab1.setText("聊天室--用戶登錄");
jContentPane = new JPanel();
jContentPane.setLayout(null);
jContentPane.add(lab1, null);
jContentPane.add(lab2, null);
jContentPane.add(lab3, null);
jContentPane.add(getUserNameField(), null);
jContentPane.add(getPasswordField(), null);
jContentPane.add(getLoginButton(), null);
jContentPane.add(getCancelButton(), null);
}
return jContentPane;
}
}
4:客戶端管理socket類
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
/**
* 該類定義客戶端的全局參數(shù),如:Socket,當前用戶,流對象等
*
*/
public class ClientModel {
private Socket socket;
private User currentUser;
private BufferedReader br;
private PrintWriter pw;
private String hostName;
private int port;
public Socket getSocket() {
return socket;
}
public ClientModel(String hostName, int port) {
super();
this.hostName = hostName;
this.port = port;
}
public User getCurrentUser() {
return currentUser;
}
public void setCurrentUser(User currentUser) {
this.currentUser = currentUser;
}
public synchronized Socket createSocket(){
if(socket==null){
try {
socket=new Socket(hostName,port);
}catch (IOException e) {
e.printStackTrace();
return null;
}
}
return socket;
}
public synchronized BufferedReader getInputStream(){
if (br==null) {
try {
br = new BufferedReader(new InputStreamReader(socket
.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
return br;
}
public synchronized PrintWriter getOutputStream(){
if (pw==null) {
try {
pw = new PrintWriter(socket.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
return pw;
}
public synchronized void closeSocket(){
if(socket!=null){
try {
br.close();
pw.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
socket=null;
br=null;
pw=null;
}
}
這里是工具和POJO類:
User類:
import java.io.Serializable;
public class User implements Serializable {
private static final long serialVersionUID = 1986L;
private int id;
private String name;
private String password;
private String email;
public User(){}
public User( String name, String password, String email) {
super();
this.name = name;
this.password = password;
this.email = email;
}
public User( String name, String password) {
super();
this.name = name;
this.password = password;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String toString(){
return id+":"+name+":"+password+":"+email;
}
}
DAO,用于從本地讀取配置文件
接口:
public interface UserDao {
public boolean addUser(User user);
public User getUser(String userName,String password);
}
實現(xiàn)類:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
public class UserDaoForTextFile implements UserDao{
private File userFile;
public UserDaoForTextFile(){
}
public UserDaoForTextFile(File file){
this.userFile = file;
if(!file.exists()){
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public synchronized boolean addUser(User user) {
FileInputStream fis = null;
BufferedReader br = null;
int lastId = 0;
try{
fis = new FileInputStream(userFile);
br = new BufferedReader(new InputStreamReader(fis));
String str = null;
String lastLine = null;
while((str=br.readLine()) != null){
//得到最后一行值
lastLine = str;
if(str.split(":")[1].equals(user.getName())){
return false;
}
}
if(lastLine != null)
lastId = Integer.parseInt(lastLine.split(":")[0]);
}catch(Exception e){
e.printStackTrace();
}finally{
if(br!=null)try{br.close();}catch(IOException e){}
if(fis!=null)try{fis.close();}catch(IOException e){}
}
FileOutputStream fos = null;
PrintWriter pw = null;
try{
fos = new FileOutputStream(userFile,true);
pw = new PrintWriter(fos);
user.setId(lastId+1);
pw.println(user);
pw.flush();
return true;
}catch(Exception e){
e.printStackTrace();
}finally{
if(pw!=null)try{pw.close();}catch(Exception e){}
if(fos!=null)try{fos.close();}catch(IOException e){}
}
return false;
}
public synchronized User getUser(String userName, String password) {
FileInputStream fis = null;
BufferedReader br = null;
String str = null;
User user = null;
try{
fis = new FileInputStream(userFile);
br = new BufferedReader(new InputStreamReader(fis));
while((str = br.readLine()) != null){
String[] s = str.split(":");
if(userName.equals(s[1]) password.equals(s[2])){
user = new User();
user.setId(Integer.parseInt(s[0]));
user.setName(s[1]);
user.setPassword(s[2]);
user.setEmail(s[3]);
}
}
}catch(IOException e){
e.printStackTrace();
}finally{
if(br!=null)try{br.close();}catch(IOException e){}
if(fis!=null)try{fis.close();}catch(IOException e){}
}
return user;
}
}
配置文件格式為:
id流水號:用戶名:密碼:郵箱
1:yawin:034437:yawin@126.com
2:zhoujg:034437:zhou@126.com
客戶端
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.net.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;
/**
*
* @author Administrator
*/
public class Main extends JFrame{
JPanel jp;
JButton jb;
javax.swing.JTextField jt1;
JTextField jt2;
JTextField jt3;
JLabel jl1;
JLabel jl2;
public Main()
{
this.setBounds(150, 50, 300, 100);
jp= new JPanel(new GridLayout(3, 2));
jb=new JButton("登陸");
jt1=new JTextField();
jt2=new JTextField();
jt3=new JTextField();
jt3.setEditable(false);
jl1=new JLabel("用戶名");
jl2=new JLabel("密碼");
this.getContentPane().add(jp);
jp.add(jl1);
jp.add(jt1);
jp.add(jl2);
jp.add(jt2);
jp.add(jt3);
jp.add(jb);
this.setVisible(true);
jb.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String sentence;
String modifiedSentence = null;
//BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
Socket clientSocket = null;
try {
clientSocket = new Socket("127.0.0.1", 6789);
} catch (UnknownHostException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
//System.out.println("connection ok");
DataOutputStream outToServer = null;
try {
outToServer = new DataOutputStream(clientSocket.getOutputStream());
} catch (IOException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
BufferedReader inFromServer = null;
try {
inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
} catch (IOException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
sentence=jt1.getText()+" "+jt2.getText();
try {
//System.out.println(sentence);
outToServer.writeBytes(sentence + '\n');
} catch (IOException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
try {
modifiedSentence = inFromServer.readLine();
} catch (IOException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
//System.out.println("FROM SERVER:"+modifiedSentence);
jt3.setText(modifiedSentence);
try {
clientSocket.close();
} catch (IOException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws Exception
{
Main m=new Main();
}
}
服務(wù)器端
import java.io.*;
import java.net.*;
public class Main {
public static void main(String[] args) throws Exception {
String clientSentence;
String capitalizedSentence;
ServerSocket welcomeSocket=new ServerSocket(6789);
while(true){
Socket connectionSocket=welcomeSocket.accept();
BufferedReader inFromClient=new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
DataOutputStream outToClient=new DataOutputStream(connectionSocket.getOutputStream());
clientSentence=inFromClient.readLine();
//capitalizedSentence=clientSentence.toUpperCase()+'\r'+'\n';
//outToClient.writeBytes(capitalizedSentence);
if(clientSentence.equalsIgnoreCase("admin 1234"))
outToClient.writeBytes("ok"+'\n');
else
outToClient.writeBytes("error"+'\n');
}
}
}
用Socket類去連接
String ip = "192.168.0.57";
int port=7000;
InputStream in;
OutputStream out;
Socket sock = null;
try {
sock = new Socket(ip,port);
sock.setSoTimeout(60*1000);//設(shè)置超時
this.in = sock.getInputStream();
this.out = sock.getOutputStream();
} catch (Exception e) {
throw new Exception("與終端連接失敗!");
}
當前文章:java登陸服務(wù)器代碼 java代碼部署服務(wù)器
瀏覽路徑:http://muchs.cn/article0/docopoo.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供搜索引擎優(yōu)化、面包屑導(dǎo)航、網(wǎng)站排名、品牌網(wǎng)站制作、網(wǎng)站設(shè)計公司、標簽優(yōu)化
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)