佳礼资讯网

 找回密码
 注册

ADVERTISEMENT

查看: 1761|回复: 10

Java Sychronization问题,求助

[复制链接]
发表于 8-11-2015 11:28 PM | 显示全部楼层 |阅读模式
小弟有一个Java TCP project,一开始有三个class,本来是没有GUI的,过后我自己加了GUI后,就出现了一下问题

这个是GUI

这个是GUI


一开始TCPServer会跟TCPClient建立connection,过后TCPClient会要去user进answer,然后由TCPProtocol来process answer再发给Server,差不多是那样的概念,先贴上我的code先

TCPClient
  1. import java.io.*;
  2. import java.net.*;

  3. public class TCPClient{
  4.             
  5.          public Object lock = new Object();
  6.          
  7.     public static void main(String[] args)  throws IOException, InterruptedException{
  8.            
  9.             //TCP component
  10.             int port = 8081;
  11.             String host = "localhost";
  12.         Socket nisSocket = null;
  13.         PrintWriter out = null;
  14.         BufferedReader in = null;
  15.         TCPClient t = new TCPClient();
  16.         
  17.         try {
  18.             nisSocket = new Socket(host, port);
  19.             out = new PrintWriter(nisSocket.getOutputStream(), true);
  20.             in = new BufferedReader(new InputStreamReader(nisSocket.getInputStream()));
  21.         } catch (UnknownHostException e) {
  22.             System.out.println(e.toString() + " :Don't know about " + host);
  23.             System.exit(1);
  24.         } catch (IOException e) {
  25.             System.out.println(e.toString() + " :Couldn't get I/O for the connection to " + host);
  26.             System.exit(1);
  27.         }

  28.         BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
  29.         String fromServer, fromUser;
  30.         
  31.         while ((fromServer = in.readLine()) != null) {
  32.                     System.out.println("Server: " + fromServer);
  33.             if (fromServer.equalsIgnoreCase("Don't miss me! Bye Bye!"))
  34.                 break;
  35.                         if (fromServer.equalsIgnoreCase("Thank For Your Guessing. Have a Nice Day =)"))
  36.                 break;
  37.                        
  38.                          while (true) {
  39.                             synchronized (t.lock) {
  40.                                 try {
  41.                                     t.lock.wait();
  42.                                     TCPProtocol abc = new TCPProtocol();
  43.                                     System.out.println("try again");
  44.                                     fromUser = abc.Jusertxt.getText().toString();
  45.                                     System.out.println("\nClient: " + fromUser);
  46.                                         out.println(fromUser);
  47.                                 }
  48.                                 catch (InterruptedException e) {
  49.                                     e.printStackTrace();
  50.                                 }

  51.                             }
  52.                         }
  53.                
  54.         }
  55.         System.out.println("try again");
  56.         //End connection
  57.         out.flush();
  58.         out.close();        
  59.         in.close();
  60.         stdIn.close();
  61.         
  62.         //if (!nisSocket.isClosed())
  63.                 nisSocket.close();
  64.         System.out.println("TCP session closed.");
  65.     }
  66.    
  67.     public String pullText(){
  68.            
  69.             TCPProtocol pro = new TCPProtocol();
  70.             String result = pro.Jusertxt.getText().toString();
  71.         pro.Jusertxt.setText("");
  72.         return result;
  73.     }
  74.    
  75. }
复制代码
TCPProtocol
  1. import java.awt.*;
  2. import java.awt.event.ActionEvent;
  3. import java.awt.event.ActionListener;
  4. import java.util.Random;
  5. import javax.swing.*;

  6. public class TCPProtocol extends JFrame{
  7.    
  8.         public JFrame frame;
  9.         public JTextArea Jservertxt, Jusertxt;
  10.         public JLabel label;
  11.         public String usertxt, servertxt;
  12.         public JButton Jsend;
  13.         private JScrollPane scl, Uscl;
  14.         private boolean getPressed =false;
  15.        
  16.        
  17.         String init = "Hi, i am your lame joker. Are you ready to play now?<Y/N>";
  18.                         
  19.     String correct ="Great Job! You are Correct!";
  20.    
  21.     String[] riddle = {"What do you call a fake noodle?",
  22.                    "why did the turtle cross the road?",
  23.                    "Why shouldn't you believe a man in bed?",
  24.                    "Which  travels faster, heat or cold?",
  25.                    "Why do UKM Students feel stronger on Saturday and Sunday?",
  26.                    "What do you call a sleeping bull?",
  27.                    "They come out at night without being called, and are lost in the day without being stolen. What are they?",
  28.            "What comes down but never goes up?",
  29.            "What has one eye but cannot see?",
  30.            "What kind of tree can you carry in your hand?",
  31.            "How do you make the number one disappear?",
  32.            "What goes up but never comes down?",
  33.            "We see it once in a year, twice in a week, and never in a day. What is it?",
  34.            "How many months have 28 days?",
  35.            "If a blue house is made out of blue bricks, a yellow house is made out of yellow bricks and a pink house is made out of pink bricks, what is a green house made of?",
  36.            "What goes up a chimney down but can? come down a chimney up?",
  37.            "What is at the end of a rainbow?",
  38.            "What can you catch but not throw?",
  39.            "What is as light as a feather, but even the world? strongest man couldn? hold it for more than a minute?"};
  40.    
  41.     String[] answer = {"Impasta",
  42.                     "shell station",
  43.                     "lying",
  44.                     "cold",
  45.                     "week day",
  46.                     "bulldozer",
  47.                     "stars",
  48.             "rain",
  49.             "needle",
  50.             "palm",
  51.             "letter",
  52.             "your ",
  53.             "e",
  54.             "all",
  55.             "glass",
  56.             "umbrella",
  57.             "letter w",
  58.             "cold",
  59.             "breath"};
  60.    
  61.    String [] actualAnswer = {"Impasta",
  62.                    "To get to the shell station.",
  63.                    "Because he is lying.",
  64.                    "Heat. Because you can catch 'cold' easily.",
  65.                    "Because all the other days are week (weak) days.",
  66.                    "A bulldozer!",
  67.                    "S (Stars)",
  68.            "R (Rain)",
  69.            "N (A needle)",
  70.            "P (A palm!)",
  71.            "L (Add the letter G and it? GONE)",
  72.            "Y (Your age!) ",
  73.            "E (The letter ??",
  74.            "M (All 12 months!)",
  75.            "G (Glass)",
  76.            "U (An umbrella)",
  77.            "W (The letter W!)",
  78.            "C (A cold)",
  79.            "B (His breath!)"};
  80.    
  81.     String next = "Ready For Next Question? <Y/N>";
  82.     //String next = "Do you have exercise often?";
  83.    
  84.     //String isOk = "Is ok. Give It A Try Next Time. Have a Nice Day =)";
  85.     String isOk = "Don't miss me! Bye Bye!";
  86.    
  87.     //String bye = "Thank For Your Guessing. Have a Nice Day =)";
  88.     String bye="I Wont't Deactivated Until You Say Are Happy With My Joke.";
  89.    
  90.     String again = "Play Again? <Y/N>";
  91.    
  92.     int INITIAL = 0;
  93.     int STEP1 = 1;  //asking question part
  94.     int STEP2 = 2;  //confirm answer part
  95.     int question = 0;
  96.     int noOfQuestionAnswered = 0;
  97.     int state = INITIAL;
  98.     String comp;
  99.    
  100.     public String processAnswer(String input)
  101.     {
  102.         String output = null;      
  103.         
  104.         if (state == STEP1) //asking question part
  105.         {
  106.             if (input.equalsIgnoreCase("y"))
  107.             {
  108.                 output = riddle[question];
  109.                 state = STEP2;         
  110.             }
  111.             else
  112.             {   
  113.                     if(input.indexOf("Satisfied") != -1)
  114.                     {
  115.                             if (noOfQuestionAnswered == 0)
  116.                                     output = isOk;
  117.                             else
  118.                                     output = bye;
  119.                     }
  120.                     else
  121.                     {
  122.                                     output = isOk;
  123.                     }
  124.             }      
  125.         }
  126.         
  127.         else if (state == STEP2) // confirm answer part
  128.         {   
  129.                 if (input.indexOf(answer[question]) != -1)
  130.             {
  131.                 output = correct +next;
  132.                 state = STEP1;
  133.             }
  134.             else
  135.             {
  136.                 output = "Oh no, you answer wrongly ! "+ "Correct Answer: " + actualAnswer[question]+ " . " + again;   
  137.                 state = STEP1;
  138.             }
  139.         
  140.             question = (question + 1) % 19;
  141.             noOfQuestionAnswered++;
  142.         }
  143.         
  144.         else if (state == INITIAL)
  145.         {      
  146.             output = init;//"Learn Learn English. Are you ready to play now?<Y?N>(try to get Y/N)"
  147.             state = STEP1;
  148.             Random rand = new Random();

  149.             question = rand.nextInt(18);
  150.         }
  151.             
  152.         return output;      
  153.     }
  154.    
  155.     public static void main(String[] args) {
  156.                 EventQueue.invokeLater(new Runnable() {
  157.                         public void run() {
  158.                                 try {
  159.                                         TCPProtocol window = new TCPProtocol();
  160.                                         window.frame.setVisible(true);
  161.                                 } catch (Exception e) {
  162.                                         e.printStackTrace();
  163.                                 }
  164.                         }
  165.                 });

  166.         }
  167.            
  168.             public TCPProtocol()
  169.             {
  170.            
  171.                     initialize();
  172.             }
  173.            
  174.             public void initialize() {
  175.                    
  176.                     frame = new JFrame("Lame Joker");
  177.                     frame.setBounds(300,150,480,450);
  178.                     frame.getContentPane().setLayout(new GridLayout());
  179.                     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  180.                     frame.setContentPane(new JLabel(new ImageIcon("C:\\Users\\lenovo\\Desktop\\Network Programming\\Project\\baymax.jpg")));
  181.                     Jservertxt = new JTextArea(5,5);
  182.                     Jservertxt.setEditable(false);
  183.                     Jservertxt.setLineWrap(true);
  184.                     Jusertxt = new JTextArea(5,5);
  185.                    
  186.                     scl = new JScrollPane(Jservertxt);
  187.                     scl.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
  188.                     scl.setBounds(0, 0, 465, 45);
  189.                     Uscl = new JScrollPane(Jusertxt);
  190.                     Uscl.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
  191.                     Uscl.setBounds(0, 368, 395, 45);
  192.                     Jsend = new JButton("Send");
  193.                     Jsend.setBounds(394, 368, 71, 46);//(leftright,updown,sizewidth,sizeheight)
  194.                     frame.getContentPane().add(scl);
  195.                     frame.getContentPane().add(Uscl);
  196.                     frame.getContentPane().add(Jsend);
  197.                    
  198.                     Jsend.addActionListener(new ActionListener() {
  199.                         public void actionPerformed(ActionEvent e) {
  200.                                
  201.                                 //String Data = Jusertxt.getText();
  202.                                 //System.out.println(Data);
  203.                                 //getPressed=true;
  204.                                 TCPClient client = new TCPClient();
  205.                                 synchronized(client.lock){
  206.                                         //String Data = Jusertxt.getText();
  207.                                     //System.out.println(Data);
  208.                                         client.lock.notify();
  209.                                 }
  210.                                
  211.             }
  212.                     });
  213.            
  214.             }
  215.            
  216.             public boolean getPressed()
  217.             {
  218.                     return getPressed;
  219.             }
  220.    
  221. }
复制代码
TCPServer
  1. import java.net.*;
  2. import java.io.*;

  3. public class TCPServer {
  4.        
  5.     public static void main(String[] args) throws IOException {
  6.            
  7.             //TCP component
  8.             ServerSocket serverSocket = null;
  9.             Socket clientSocket = null;
  10.             int port = 8081;
  11.             TCPProtocol nis = new TCPProtocol();//create an object to call method in protocol class
  12.                    
  13.         try {
  14.             serverSocket = new ServerSocket(port);
  15.             System.out.println("Waiting for connection...");
  16.             System.out.println();
  17.         } catch (IOException e) {
  18.             System.out.println(e.toString() + " :Could not listen on port: " + port);
  19.             System.exit(1);
  20.         }
  21.         
  22.         
  23.         try {
  24.             clientSocket = serverSocket.accept();
  25.             System.out.println("TCP Session established.");
  26.             nis.frame.setVisible(true);
  27.             nis.frame.setAlwaysOnTop(true);
  28.             System.out.println();
  29.             
  30.         } catch (IOException e) {
  31.             System.out.println(e.toString() + " :Accept failed.");
  32.             System.exit(1);
  33.         }

  34.         PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
  35.         BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
  36.                
  37.         String inputLine, outputLine;
  38.         outputLine = nis.processAnswer(null);//get Learn Learn English line
  39.         out.println(outputLine);//and send the line out to client
  40.         nis.Jservertxt.setText(outputLine);
  41.         
  42.         while ((inputLine = in.readLine()) != null) {
  43.              outputLine = nis.processAnswer(inputLine);
  44.              out.println(outputLine);
  45.              nis.Jservertxt.setText(outputLine);
  46.              if (outputLine.equalsIgnoreCase("Don't miss me! Bye Bye!"))
  47.                 break;
  48.                          else if (outputLine.equalsIgnoreCase("Thank For Your Guessing. Have a Nice Day =)"))
  49.                 break;
  50.         }
  51.         
  52.         //End connection
  53.         out.flush();
  54.         out.close();
  55.         in.close();
  56.         nis.frame.setVisible(false);
  57.         if (!clientSocket.isClosed())
  58.                 clientSocket.close();
  59.                 nis.frame.setVisible(false);
  60.         if (!serverSocket.isClosed())
  61.                 serverSocket.close();
  62.                 nis.frame.setVisible(false);
  63.         
  64.         System.out.println("TCP session closed.");
  65.     }
  66. }
复制代码
希望我的代码看起来不会太乱,我是做synchronize在Jsend button一按,才notify TCPClient的thread,可是做来作曲不成功

试了很多办法了,希望哪位大大可以帮忙小弟

回复

使用道具 举报


ADVERTISEMENT

发表于 13-11-2015 11:19 AM | 显示全部楼层
你的概念其实也没错,问题就在你把 Protocol 和 UI 混在一起(很乱)。 你应该把他们分开, protocol 处理logic UI 负责显示。server 直接access UI就错了。
  1. nis.frame.setVisible(false);
复制代码

你可以把Protocol 的 Method 改成 static
  1. TCPProtocol nis = new TCPProtocol();// create an object to call method
  2.                                                                                         // in protocol class
复制代码

就可以省掉这行

如果想要搞好这个 project 实在是建议你先把代码整理干净。
还有我看到
  1.   public String pullText(){
  2.             
  3.             TCPProtocol pro = new TCPProtocol();
  4.             String result = pro.Jusertxt.getText().toString();
  5.         pro.Jusertxt.setText("");
  6.         return result;
  7.     }
复制代码

根本没被 call 到。
  1. public class TCPProtocol extends JFrame {

  2.         public JFrame frame;
复制代码

既然 inherit 了 JFrame 干嘛又做多一个instance。
记得把显示的功能搬到 client 去

评分

参与人数 1积分 +5 人气 +1 收起 理由
musicalangel + 5 + 1 谢谢分享

查看全部评分

回复

使用道具 举报

 楼主| 发表于 13-11-2015 12:05 PM | 显示全部楼层
kst9395 发表于 13-11-2015 11:19 AM
你的概念其实也没错,问题就在你把 Protocol 和 UI 混在一起(很乱)。 你应该把他们分开, protocol 处理l ...

因为一开始这个代码是老师给的(用CMD或者console里面input而已),老师要我们自己加GUI,然后老师也指定只可以在TCPProtocolClass modify而已,所以唯有那样改
谢谢你的指点
回复

使用道具 举报

发表于 13-11-2015 12:13 PM | 显示全部楼层
本帖最后由 kst9395 于 13-11-2015 12:17 PM 编辑
shern91 发表于 13-11-2015 12:05 PM
因为一开始这个代码是老师给的(用CMD或者console里面input而已),老师要我们自己加GUI,然后老师也指定只 ...

加gui 其实也没必要让protocol extends JFrame。你可以在Client class 加一个JFrame。软件工程有一个概念叫 separation of concern,就是让各个 component 做自己的事情, 比如 protocol 只做input process 而不做 display 然后server 负责传话。我其实也不太明白为什么需要用到 lock。你的 server 和client 本来就用着不同的 TCPProtocol object,这样lock 好像没意义。

P/S:我java se 其实也只学到 file +thread 而已,socket 没有很深入。java ee 倒是比较在行 LOL

题外话:Swing 真的很邪恶(如果真的必须用就没办法),用code来define gui 是很痛苦的事情,做完这个建议去看看JavaFx,共勉之

评分

参与人数 1积分 +5 人气 +1 收起 理由
musicalangel + 5 + 1 谢谢分享

查看全部评分

回复

使用道具 举报

 楼主| 发表于 13-11-2015 12:22 PM | 显示全部楼层
kst9395 发表于 13-11-2015 12:13 PM
加gui 其实也没必要让protocol extends JFrame。你可以在Client class 加一个JFrame。软件工程有一个概念 ...

刚刚听了大大的建议,我改了一些code,把display的code放在client那边call,虽然看起来还是很乱,不过我做到了

我最新的code是stackoverflow里面有一个网友帮我的

TCPProtcol.java
  1. import java.awt.*;
  2. import java.awt.event.ActionEvent;
  3. import java.awt.event.ActionListener;
  4. import java.util.Random;
  5. import javax.swing.*;

  6. public class TCPProtocol extends JFrame{
  7.    
  8.         public JFrame frame;
  9.         public JTextArea Jservertxt, Jusertxt;
  10.         public JLabel label;
  11.         public String usertxt, servertxt;
  12.         public JButton Jsend;
  13.         private JScrollPane scl, Uscl;
  14.         private volatile boolean getPressed = false;
  15.         //private boolean getPressed = false;
  16.         private Object lock = new Object(); // added lock for wait/notify coordination
  17.         private String Data ; //changed scope to make it accessible in getMessage()
  18.        
  19.         String init = "Hi, i am your lame joker. Are you ready to play now?<Y/N>";
  20.                         
  21.     String correct ="Great Job! You are Correct!";
  22.    
  23.     String[] riddle = {"What do you call a fake noodle?",
  24.                    "why did the turtle cross the road?",
  25.                    "Why shouldn't you believe a man in bed?",
  26.                    "Which  travels faster, heat or cold?",
  27.                    "Why do UKM Students feel stronger on Saturday and Sunday?",
  28.                    "What do you call a sleeping bull?",
  29.                    "They come out at night without being called, and are lost in the day without being stolen. What are they?",
  30.            "What comes down but never goes up?",
  31.            "What has one eye but cannot see?",
  32.            "What kind of tree can you carry in your hand?",
  33.            "How do you make the number one disappear?",
  34.            "What goes up but never comes down?",
  35.            "We see it once in a year, twice in a week, and never in a day. What is it?",
  36.            "How many months have 28 days?",
  37.            "If a blue house is made out of blue bricks, a yellow house is made out of yellow bricks and a pink house is made out of pink bricks, what is a green house made of?",
  38.            "What goes up a chimney down but can? come down a chimney up?",
  39.            "What is at the end of a rainbow?",
  40.            "What can you catch but not throw?",
  41.            "What is as light as a feather, but even the world? strongest man couldn? hold it for more than a minute?"};
  42.    
  43.     String[] answer = {"Impasta",
  44.                     "shell station",
  45.                     "lying",
  46.                     "cold",
  47.                     "week day",
  48.                     "bulldozer",
  49.                     "stars",
  50.             "rain",
  51.             "needle",
  52.             "palm",
  53.             "letter",
  54.             "your ",
  55.             "e",
  56.             "all",
  57.             "glass",
  58.             "umbrella",
  59.             "letter w",
  60.             "cold",
  61.             "breath"};
  62.    
  63.    String [] actualAnswer = {"Impasta",
  64.                    "To get to the shell station.",
  65.                    "Because he is lying.",
  66.                    "Heat. Because you can catch 'cold' easily.",
  67.                    "Because all the other days are week (weak) days.",
  68.                    "A bulldozer!",
  69.                    "S (Stars)",
  70.            "R (Rain)",
  71.            "N (A needle)",
  72.            "P (A palm!)",
  73.            "L (Add the letter G and it? GONE)",
  74.            "Y (Your age!) ",
  75.            "E (The letter ??",
  76.            "M (All 12 months!)",
  77.            "G (Glass)",
  78.            "U (An umbrella)",
  79.            "W (The letter W!)",
  80.            "C (A cold)",
  81.            "B (His breath!)"};
  82.    
  83.     String next = "Ready For Next Question? <Y/N>";
  84.     //String next = "Do you have exercise often?";
  85.    
  86.     //String isOk = "Is ok. Give It A Try Next Time. Have a Nice Day =)";
  87.     String isOk = "Don't miss me! Bye Bye!";
  88.    
  89.     //String bye = "Thank For Your Guessing. Have a Nice Day =)";
  90.     String bye="I Wont't Deactivated Until You Say Are Happy With My Joke.";
  91.    
  92.     String again = "Play Again? <Y/N>";
  93.    
  94.     int INITIAL = 0;
  95.     int STEP1 = 1;  //asking question part
  96.     int STEP2 = 2;  //confirm answer part
  97.     int question = 0;
  98.     int noOfQuestionAnswered = 0;
  99.     int state = INITIAL;
  100.     String comp;
  101.    
  102.     public String processAnswer(String input)
  103.     {
  104.         String output = null;      
  105.         
  106.         if (state == STEP1) //asking question part
  107.         {
  108.             if (input.equalsIgnoreCase("y"))
  109.             {
  110.                 output = riddle[question];
  111.                 state = STEP2;         
  112.             }
  113.             else
  114.             {   
  115.                     if(input.indexOf("Satisfied") != -1)
  116.                     {
  117.                             if (noOfQuestionAnswered == 0)
  118.                                     output = isOk;
  119.                             else
  120.                                     output = bye;
  121.                     }
  122.                     else
  123.                     {
  124.                                     output = isOk;
  125.                     }
  126.             }      
  127.         }
  128.         
  129.         else if (state == STEP2) // confirm answer part
  130.         {   
  131.                 if (input.indexOf(answer[question]) != -1)
  132.             {
  133.                 output = correct +next;
  134.                 state = STEP1;
  135.             }
  136.             else
  137.             {
  138.                 output = "Oh no, you answer wrongly ! "+ "Correct Answer: " + actualAnswer[question]+ " . " + again;   
  139.                 state = STEP1;
  140.             }
  141.         
  142.             question = (question + 1) % 19;
  143.             noOfQuestionAnswered++;
  144.         }
  145.         
  146.         else if (state == INITIAL)
  147.         {      
  148.             output = init;//"Learn Learn English. Are you ready to play now?<Y?N>(try to get Y/N)"
  149.             state = STEP1;
  150.             Random rand = new Random();

  151.             question = rand.nextInt(18);
  152.         }
  153.             
  154.         return output;      
  155.     }
  156.    
  157.     public static void main(String[] args) {
  158.                 EventQueue.invokeLater(new Runnable() {
  159.                         public void run() {
  160.                                 try {
  161.                                         TCPProtocol window = new TCPProtocol();
  162.                                         window.frame.setVisible(true);
  163.                                 } catch (Exception e) {
  164.                                         e.printStackTrace();
  165.                                 }
  166.                         }
  167.                 });

  168.         }
  169.            
  170.             public TCPProtocol()
  171.             {
  172.            
  173.                     initialize();
  174.             }
  175.            
  176.             public void initialize() {
  177.                    
  178.                     frame = new JFrame("Lame Joker");
  179.                     frame.setBounds(300,150,480,450);
  180.                     frame.getContentPane().setLayout(new GridLayout());
  181.                     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  182.                     frame.setContentPane(new JLabel(new ImageIcon("C:\\Users\\lenovo\\Desktop\\Network Programming\\Project\\baymax.jpg")));
  183.                     Jservertxt = new JTextArea(5,5);
  184.                     Jservertxt.setEditable(false);
  185.                     Jservertxt.setLineWrap(true);
  186.                     Jusertxt = new JTextArea(5,5);
  187.                     //Jusertxt.setVisible(false);
  188.                    
  189.                     scl = new JScrollPane(Jservertxt);
  190.                     scl.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
  191.                     scl.setBounds(0, 0, 465, 45);
  192.                     Uscl = new JScrollPane(Jusertxt);
  193.                     Uscl.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
  194.                     Uscl.setBounds(0, 368, 395, 45);
  195.                     Jsend = new JButton("Send");
  196.                     Jsend.setBounds(394, 368, 71, 46);//(leftright,updown,sizewidth,sizeheight)
  197.                     frame.getContentPane().add(scl);
  198.                     frame.getContentPane().add(Uscl);
  199.                     frame.getContentPane().add(Jsend);
  200.                    
  201.                     Jsend.addActionListener(new ActionListener() {
  202.                         public void actionPerformed(ActionEvent e) {
  203.                                
  204.                                 synchronized(lock){
  205.                                         //lock.notify();
  206.                                         Data = Jusertxt.getText();
  207.                                         Jusertxt.setText(null);
  208.                                         System.out.println(Data);
  209.                                         getPressed=true;
  210.                                         lock.notify();
  211.                                         //System.out.println("unlock");
  212.                                        
  213.                                 }
  214.                                
  215.             }
  216.                     });
  217.            
  218.             }
  219.            
  220.             public boolean getPressed(){
  221.                 synchronized (lock) {
  222.                     try {
  223.                         lock.wait(); // wait for user to perform action...
  224.                     }
  225.                     catch (InterruptedException e) {
  226.                         e.printStackTrace();
  227.                     }
  228.                 }
  229.                 System.out.println("success return true");
  230.                 return getPressed; // ...then return value (I guess getPressed will always be true at this point)
  231.             }

  232.             public String getMessage(){ // call this in TCPClient instead of pro.Jusertxt.getText()
  233.                 return Data;
  234.             }
  235.    
  236. }
复制代码
TCPClient.java
  1. import java.io.*;
  2. import java.net.*;

  3. public class TCPClient{
  4.             
  5.          public final Object lock = new Object();
  6.          
  7.     public static void main(String[] args)  throws IOException{
  8.            
  9.             //TCP component
  10.             int port = 8081;
  11.             String host = "localhost";
  12.         Socket nisSocket = null;
  13.         PrintWriter out = null;
  14.         BufferedReader in = null;
  15.         TCPProtocol pro = new TCPProtocol();
  16.         
  17.         try {
  18.             nisSocket = new Socket(host, port);
  19.             out = new PrintWriter(nisSocket.getOutputStream(), true);
  20.             in = new BufferedReader(new InputStreamReader(nisSocket.getInputStream()));
  21.         } catch (UnknownHostException e) {
  22.             System.out.println(e.toString() + " :Don't know about " + host);
  23.             System.exit(1);
  24.         } catch (IOException e) {
  25.             System.out.println(e.toString() + " :Couldn't get I/O for the connection to " + host);
  26.             System.exit(1);
  27.         }

  28.         BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
  29.         String fromServer, fromUser;
  30.         
  31.         while ((fromServer = in.readLine()) != null) {
  32.                     System.out.println("Server: " + fromServer);
  33.             if (fromServer.equalsIgnoreCase("Don't miss me! Bye Bye!"))
  34.                 break;
  35.                         if (fromServer.equalsIgnoreCase("Thank For Your Guessing. Have a Nice Day =)"))
  36.                 break;
  37.                        
  38.                         pro.frame.setVisible(true);
  39.             pro.frame.setAlwaysOnTop(true);
  40.             pro.Jservertxt.setText(fromServer);
  41.                         if(pro.getPressed()){
  42.                                 //System.out.println("after press");
  43.                                 fromUser = pro.getMessage();
  44.                                 //System.out.println("fromUser value "+fromUser);
  45.                                         if (fromUser != null) {
  46.                                                         System.out.println("\nClient: " + fromUser);
  47.                                                         out.println(fromUser);
  48.                                         }
  49.                         }
  50. //                        else
  51. //                        {
  52. //                                System.out.println("din get");
  53. //                        }
  54.         }
  55.         System.out.println("try again");
  56.         //End connection
  57.         out.flush();
  58.         out.close();        
  59.         in.close();
  60.         stdIn.close();
  61.         
  62.         //if (!nisSocket.isClosed())
  63.                 nisSocket.close();
  64.         System.out.println("TCP session closed.");
  65.     }
  66.    
  67. }
复制代码
我把display放进while{}里面,结果成功了,还不是很懂为什么在server就失败,在client那边就成功
回复

使用道具 举报

发表于 13-11-2015 12:31 PM | 显示全部楼层
shern91 发表于 13-11-2015 12:22 PM
刚刚听了大大的建议,我改了一些code,把display的code放在client那边call,虽然看起来还是很乱,不过我 ...

虽然做到了是好事,但是还是搞清楚怎么回事,it work but I don't know why是大忌
你的 tcpprotocol object 也就是jframe 在client 和 server 各有一个。你update 了client 的object 却显示 server 的object。这大概就是其中的原因.
  1. nis.frame.show();//我记得这个有在server 出现过
复制代码


回复

使用道具 举报

Follow Us
 楼主| 发表于 13-11-2015 12:54 PM | 显示全部楼层
kst9395 发表于 13-11-2015 12:31 PM
虽然做到了是好事,但是还是搞清楚怎么回事,it work but I don't know why是大忌
你的 tcpprotocol  ...
  1. nis.frame.show();//我记得这个有在server 出现过
复制代码
拿个代码应该行不通的,要用,可是我刚刚check了server里面没有
  1. frame.setVisible(true);
复制代码
之前把call GUI的code放在server,行不通,system跑到以下的code就走不到了,即使我有放else再system.out.print还是打印不到任何字,就当我stuck在这边时大大建议我换去client call GUI时就奇迹般的行得通,也不知道为何 不过会尝试试看了解一下下。其余code我都懂system是怎样跑的。
  1. if(pro.getPressed()){
  2.                                 fromUser = pro.getMessage();
  3.                                         if (fromUser != null) {
  4.                                                         System.out.println("\nClient: " + fromUser);
  5.                                                         out.println(fromUser);
  6.                                         }
  7.                         }
复制代码


回复

使用道具 举报

发表于 13-11-2015 12:57 PM | 显示全部楼层
试看 debug mode 吧,放个break point debug 看看发生什么事。
Java se 真是讨人厌 LOL
回复

使用道具 举报


ADVERTISEMENT

 楼主| 发表于 13-11-2015 01:08 PM | 显示全部楼层
kst9395 发表于 13-11-2015 12:57 PM
试看 debug mode 吧,放个break point debug 看看发生什么事。
Java se 真是讨人厌 LOL

debug mode在eclipse里面的吗?没用过啊

break point debug又是什么来的?
回复

使用道具 举报

发表于 13-11-2015 01:15 PM | 显示全部楼层
shern91 发表于 13-11-2015 01:08 PM
debug mode在eclipse里面的吗?没用过啊

break point debug又是什么来的?

debug mode 是在很多ide 里面都有的功能,主要是在要测试的地方放一个break point,然后debug 的时候只要执行到breakpoint 就会停下让你观察variable, object 之类的。

这个video有教学。学会debug 后可以让你的programming 进步更快,你能够更了解你的program flow。共勉之

评分

参与人数 2积分 +10 人气 +10 收起 理由
musicalangel + 10 + 5 谢谢分享
shern91 + 5 谢谢分享

查看全部评分

回复

使用道具 举报

 楼主| 发表于 13-11-2015 02:30 PM | 显示全部楼层
shern91 发表于 13-11-2015 01:08 PM
debug mode在eclipse里面的吗?没用过啊

break point debug又是什么来的?

谢谢大大分享,我从来不知道有那样的东西
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 注册

本版积分规则

 

ADVERTISEMENT



ADVERTISEMENT



ADVERTISEMENT

ADVERTISEMENT


版权所有 © 1996-2023 Cari Internet Sdn Bhd (483575-W)|IPSERVERONE 提供云主机|广告刊登|关于我们|私隐权|免控|投诉|联络|脸书|佳礼资讯网

GMT+8, 4-8-2025 03:12 AM , Processed in 0.177951 second(s), 37 queries , Gzip On.

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

快速回复 返回顶部 返回列表