单客户端与服务器的传输
多客户端与服务器的传输
package com.IM;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JTextArea;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.awt.event.ActionEvent;
import javax.swing.JList;
public class MyServer extends JFrame {
//private ServerSocket server;
//private Socket socket;
private JTextArea textArea;
private DefaultListModel<String> modle;
private ArrayList<Socket> sockets;
private boolean isRunning=true;
private JPanel contentPane;
public boolean isRunning() {
return isRunning;
}
public void setRunning(boolean isRunning) {
this.isRunning = isRunning;
}
/** * Launch the application. */
public static void main(String[] args) {
//主线程的维护工作,在主线程中调用run方法
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MyServer frame = new MyServer();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/** * Create the frame. */
public MyServer() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 445, 491);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JButton button = new JButton("启动服务");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("服务器启动,等待连接");
//新建的线程是为了空出主线程,如果不新建线程,则while()运行不完,主线程运行不完
//就好像有一个人甲,要做检测"启动服务(read)","发送(write)"工作,当线程运行"启动服务"时被卡死,则不能进行"发送"
//此时需要另一个人乙来代替甲来做"启动服务"工作,甲继续检测"发送"工作,也就是新建一个线程,
new Thread(new Runnable() {
public void run() {
try {
ServerSocket server=new ServerSocket(8080);
//此处socket只能是局部变量,如果是全局变量则只能接受到最后一个断开
sockets=new ArrayList<>();
while(isRunning){
// ServerSocket server=new ServerSocket(8080);
Socket socket=server.accept();//等待连接,准备开启线程
sockets.add(socket);
Thread t=new Thread(new MyServerReadThread(MyServer.this,socket));
//建立新线程,准备开启线程,调用run方法读
t.start();
System.out.println("有客户端连接");
}
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}).start(); ;
}
});
button.setBounds(332, 10, 93, 86);
contentPane.add(button);
textArea = new JTextArea();
textArea.setBounds(10, 396, 312, 47);
contentPane.add(textArea);
JButton button_1 = new JButton("发送");
button_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
write();//进行写操作
}
});
button_1.setBounds(332, 396, 93, 23);
contentPane.add(button_1);
JList list = new JList();
list.setBounds(10, 20, 312, 344);
modle=new DefaultListModel<>();
list.setModel(modle);
contentPane.add(list);
}
public void read(Socket socket){
InputStream is;
//检测客户端口是否连接,连接则进行读操作,否则移除该端口
if(socket.isConnected()){
try {
is = socket.getInputStream();
BufferedReader br=new BufferedReader(new InputStreamReader(is));
String line=br.readLine();
modle.addElement(socket.getInetAddress()+" "+"客户端说: "+line);
System.out.println("服务器接收到信息"+"\n"+line);
} catch (IOException e) {
e.printStackTrace();
}
}else{
sockets.remove(socket);//端口断开连接时,使减少报错
}
}
public void write(){
try {
for(Socket socket:sockets){
OutputStream os=socket.getOutputStream();
BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(os));
String words=textArea.getText();//得到文本框中的内容
modle.addElement("服务器说: "+words);
System.out.println("服务器说:"+"\n"+words);
bw.write(words+"\n");
textArea.setText("");//注意写完之后清空
bw.flush();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
package com.IM;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JTextArea;
import javax.swing.DefaultButtonModel;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JList;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.awt.event.ActionEvent;
public class MyClient extends JFrame {
private Socket socket;
private JTextArea textArea;
private JPanel contentPane;
private JList list;
private DefaultListModel<String> modle;
/** * Launch the application. */
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MyClient frame = new MyClient();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/** * Create the frame. */
public MyClient() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 484, 442);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
textArea = new JTextArea();
textArea.setBounds(10, 299, 332, 78);
contentPane.add(textArea);
JButton btnNewButton = new JButton("发送");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
write();
}
});
btnNewButton.setBounds(352, 303, 106, 60);
contentPane.add(btnNewButton);
list = new JList();
list.setBounds(10, 22, 332, 268);
modle=new DefaultListModel<>();
list.setModel(modle);
contentPane.add(list);
JButton btnNewButton_1 = new JButton("连接服务器");
btnNewButton_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
System.out.println("连接");
socket=new Socket("192.168.0.35", 8080);
Thread t=new Thread(new MyClientReadThread(MyClient.this));
t.start();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
btnNewButton_1.setBounds(352, 40, 106, 67);
contentPane.add(btnNewButton_1);
}
public void read(){
// InputStream is;
//当声明写在外面时,执行modle.addElement()语句会出错
try {
InputStream is = socket.getInputStream();
BufferedReader br=new BufferedReader(new InputStreamReader(is));
String line=br.readLine();
System.out.println("我是服务器");
modle.addElement("服务器说: "+"\n"+line); //出错
System.out.println("服务器说的"+line);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void write(){
try {
OutputStream os=socket.getOutputStream();
BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(os));
String words=textArea.getText();
modle.addElement("客户说: "+"\n"+words);//
System.out.println("客户端说"+words);
bw.write(words+"\n");
textArea.setText("");
bw.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
package com.IM;
import java.net.Socket;
public class MyServerReadThread implements Runnable{
private MyServer server;
private Socket socket;
public MyServerReadThread (MyServer server,Socket socket){
this.server=server;
this.socket=socket;
}
@Override
public void run() {
while(server.isRunning()){
server.read(socket);
}
}
public MyServer getServer() {
return server;
}
public void setServer(MyServer server) {
this.server = server;
}
}
package com.IM;
public class MyClientReadThread implements Runnable{
private MyClient client;
public MyClientReadThread(MyClient client) {
this.client=client;
}
@Override
public void run() {
while(true){
client.read();
}
}
public MyClient getClient() {
return client;
}
public void setClient(MyClient client) {
this.client = client;
}
}
package com.IM;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import net.sf.json.JSONObject;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JTextArea;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
import java.awt.event.ActionEvent;
import javax.swing.JList;
public class MyServer extends JFrame {
//private ServerSocket server;
//private Socket socket;
private JTextArea textArea;
private DefaultListModel<String> modle;
//private ArrayList<Socket> sockets;
private HashMap<String, Socket> sockets;//此处使用hashmap是因为hashmap不允许重复
private boolean isRunning=true;
private JPanel contentPane;
public boolean isRunning() {
return isRunning;
}
public void setRunning(boolean isRunning) {
this.isRunning = isRunning;
}
/** * Launch the application. */
public static void main(String[] args) {
//主线程的维护工作,在主线程中调用run方法
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MyServer frame = new MyServer();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/** * Create the frame. */
public MyServer() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 445, 491);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JButton button = new JButton("启动服务");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("服务器启动,等待连接");
//新建的线程是为了空出主线程,如果不新建线程,则while()运行不完,主线程运行不完
//就好像有一个人甲,要做检测"启动服务(read)","发送(write)"工作,当线程运行"启动服务"时被卡死,则不能进行"发送"
//此时需要另一个人乙来代替甲来做"启动服务"工作,甲继续检测"发送"工作,也就是新建一个线程,
new Thread(new Runnable() {
public void run() {
try {
ServerSocket server=new ServerSocket(8080);
//此处socket只能是局部变量,如果是全局变量则只能接受到最后一个断开
sockets=new HashMap<>();
while(isRunning){
// ServerSocket server=new ServerSocket(8080);
Socket socket=server.accept();//等待连接,准备开启线程
String ip=socket.getInetAddress().getHostAddress();
sockets.put(ip,socket);
Thread t=new Thread(new MyServerReadThread(MyServer.this,socket));
t.start();
System.out.println("有客户端连接"+ip);
}
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}).start(); ;
}
});
button.setBounds(332, 10, 93, 86);
contentPane.add(button);
textArea = new JTextArea();
textArea.setBounds(10, 396, 312, 47);
contentPane.add(textArea);
JButton button_1 = new JButton("发送");
button_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
write();//进行写操作
}
});
button_1.setBounds(332, 396, 93, 23);
contentPane.add(button_1);
JList list = new JList();
list.setBounds(10, 20, 312, 344);
modle=new DefaultListModel<>();
list.setModel(modle);
contentPane.add(list);
}
public void read(Socket socket,String line){
JSONObject obj=JSONObject.fromObject(line);
System.out.println("服务器收到"+line);
String type=obj.getString("type");
// System.out.println("开始");
String time=obj.getString("time");
String to=obj.getString("to");
String from=obj.getString("from");
String msg=obj.getString("message");
Socket tosocket=sockets.get(to);
try {
OutputStream osw=tosocket.getOutputStream();
BufferedWriter bws=new BufferedWriter(new OutputStreamWriter(osw));
modle.addElement("客户端说"+msg);
bws.write(msg+"\n");//注意出错点:要加\n
bws.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//modle.addElement(socket.getInetAddress().getHostAddress()+"客户端 "+msg);
System.out.println("服务器接收到信息"+"\n"+msg);
}
public void write(){
try {
//sockets中
Set<String> keys=sockets.keySet();//得到sockets中所有的key值
Iterator it=keys.iterator();
while(it.hasNext()) {
String key=(String) it.next();//得到一个一个的key值
OutputStream os=sockets.get(key).getOutputStream();
BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(os));
String words=textArea.getText();//得到文本框中的内容
modle.addElement("服务器说: "+words);
System.out.println("服务器说:"+"\n"+words);
bw.write(words+"\n");
textArea.setText("");//注意写完之后清空
bw.flush();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
package com.IM;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.TextArea;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import net.sf.json.JSONObject;
import javax.swing.JTextArea;
import javax.swing.DefaultButtonModel;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JList;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Calendar;
import java.awt.event.ActionEvent;
public class MyClient extends JFrame {
private Socket socket;
private JTextArea textArea;
private JPanel contentPane;
private JList list;
private DefaultListModel<String> modle;
/** * Launch the application. */
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MyClient frame = new MyClient();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/** * Create the frame. */
public MyClient() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 484, 442);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
textArea = new JTextArea();
textArea.setBounds(10, 299, 332, 78);
contentPane.add(textArea);
JButton btnNewButton = new JButton("发送");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
write();
}
});
btnNewButton.setBounds(352, 303, 106, 60);
contentPane.add(btnNewButton);
list = new JList();
list.setBounds(10, 22, 332, 268);
modle=new DefaultListModel<>();
list.setModel(modle);
contentPane.add(list);
JButton btnNewButton_1 = new JButton("连接服务器");
btnNewButton_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
System.out.println("连接");
socket=new Socket("192.168.0.46", 8080);
Thread t=new Thread(new MyClientReadThread(MyClient.this));
t.start();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
btnNewButton_1.setBounds(352, 40, 106, 67);
contentPane.add(btnNewButton_1);
}
public void read(){
try {
InputStream is = socket.getInputStream();
BufferedReader br=new BufferedReader(new InputStreamReader(is));
String line=br.readLine();
//System.out.println("我是服务器");
modle.addElement("服务器说: "+"\n"+line); //出错
System.out.println("服务器说的"+line);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public String creatJson(){
JSONObject obj=new JSONObject();
String msg=textArea.getText();
obj.put("type", "to all");
obj.put("message", msg);
//获得时间 Date Calender Date time=new Date(); String time1=time.gettime();
//Calendar
Calendar calendar=Calendar.getInstance();
obj.put("time",calendar.getTimeInMillis());
obj.put("from",socket.getInetAddress().getHostName() );
obj.put("to","192.168.0.46" );
System.out.println(obj.toString());
return obj.toString();
}
public void write(){
try {
String s=creatJson();
OutputStream os=socket.getOutputStream();
BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(os));
// String words=textArea.getText();
modle.addElement("客户说: "+s);//
System.out.println("客户端说"+s);
bw.write(s+"\n");
textArea.setText("");
bw.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
package com.IM;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.Socket;
public class MyServerReadThread implements Runnable{
private MyServer server;
private Socket socket;
public MyServerReadThread (MyServer server,Socket socket){
this.server=server;
this.socket=socket;
}
@Override
public void run() {
while(true){
try {
InputStream is=socket.getInputStream();
BufferedReader br=new BufferedReader(new InputStreamReader(is));
String line=br.readLine();
server.read(socket,line);
System.out.println(line);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
package com.IM;
public class MyClientReadThread implements Runnable{
private MyClient client;
public MyClientReadThread(MyClient client) {
this.client=client;
}
@Override
public void run() {
while(true){
client.read();
}
}
}