新手求解,socket写聊天室的时候,nextLine堵塞了
今天重新写一下聊天室的时候发现,创建两个窗口,第一个窗口第一次输出后就会堵塞,纠结中··
以下是代码:
服务端:
package Inernet;
import java.awt.BorderLayout;
import
java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Scanner;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.border.EmptyBorder;
public class fffffff extends JFrame {
private JPanel contentpanel;
private JTextArea message;
private ServerSocket server;
private ArrayList<Socket> client=new ArrayList<Socket>();
private Scanner in;
private PrintWriter out;
private Socket s;
/*
* launch the main
*/
public static void main(String[] agrs)
{
fffffff frame=new fffffff();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.createThread();
}
private void createThread()
{
s=new Socket();
try {
server=new ServerSocket(6000);
} catch (
IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
while(true)
{
try {
message.append("等待连接...\n");
s=server.accept();
message.append("连接成功...."+s+"\n");
client.add(s);
new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
try {
in=new Scanner(s.getInputStream());
while(s.isConnected())
{
String str=in.nextLine();
// System.out.println(str);
message.append(str);
for(Socket i:client)
{
out=new PrintWriter(i.getOutputStream(),true);
out.println(str);
out.flush();
}
}
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}).start();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
/*
* create the frame
*/
public fffffff()
{
contentpanel=new JPanel();
setContentPane(contentpanel);
contentpanel.setBorder(new EmptyBorder(5,5,5,5));
setBounds(300, 300, 300, 300);
contentpanel.setLayout(new BorderLayout());
setTitle("服务端");
JScrollPane jscrollpanel=new JScrollPane();
contentpanel.add(jscrollpanel,BorderLayout.CENTER);
message=new JTextArea();
jscrollpanel.setViewportView(message);
}
}
客户端:
package Inernet;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.
UnknownHostException;
import java.util.Scanner;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;
public class ffff extends JFrame{
private JPanel contentpanel;
private JTextField name;
private JTextArea message;
private JTextField send_message;
private JButton send;
private Socket client;
private Scanner in;
private PrintWriter out;
/*
* launch the main
*/
public static void main(String[] agrs)
{
ffff frame=new ffff();