📄 chatserver.java
字号:
import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ChatServer extends JFrame{
private JTextField inputBox;
private JTextArea outFrame;
private ObjectOutputStream outputS;
private ObjectInputStream inputS;
private ServerSocket toserver;
private Socket server;
private int counter=1;
public ChatServer()
{
super("Server");
Container container=getContentPane();
inputBox=new JTextField();
inputBox.setEnabled(false);
inputBox.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent event)
{
sendMsg(event.getActionCommand());
}
}
);
container.add(inputBox,BorderLayout.NORTH);
outFrame=new JTextArea();
container.add(new JScrollPane(outFrame),
BorderLayout.CENTER);
setSize(280,160);
setVisible(true);
}
public void connectServer()
{
try{
toserver=new ServerSocket(4000);
while(true){
wait4Connection();
getStreams();
processConnection();
closeConnection();
++counter;
}
}
catch(EOFException eofException){
System.out.println("Client terminated connection");
}
catch(IOException ioException){
ioException.printStackTrace();
}
}
private void wait4Connection() throws IOException
{
outFrame.setText("等待连接....\n");
Socket connection=toserver.accept();
outFrame.append("Connection"+counter+"from:"+connection.getInetAddress().getHostName());
}
private void getStreams() throws IOException
{
outputS=new ObjectOutputStream(
server.getOutputStream());
outputS.flush();
inputS=new ObjectInputStream(server.getInputStream());
outFrame.append("\nGet I/O streams\n");
}
private void processConnection() throws IOException
{
String message="服务器>>连接成功";
outputS.writeObject(message);
outputS.flush();
inputBox.setEnabled(true);
do{
try{
message=(String) inputS.readObject();
outFrame.append("\n"+message);
outFrame.setCaretPosition(outFrame.getText().length());
}
catch(ClassNotFoundException classNotFoundException){
outFrame.append("\nUnknown object type received");
}
}while(!message.equals("客户端>>TERMINATE"));
}
private void closeConnection() throws IOException
{
outFrame.append("\nUser terminated connection");
inputBox.setEnabled(false);
outputS.close();
inputS.close();
server.close();
}
private void sendMsg(String message)
{
try{
outputS.writeObject("服务器端"+message);
outputS.flush();
outFrame.append("\n服务器端>>"+message);
}
catch(IOException ioException){
outFrame.append("\nErrar writing object");
}
}
public static void main(String args[])
{
ChatServer process=new ChatServer();
process.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
process.connectServer();
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -