服务段



import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;

public class Main {
private BufferedReader reader;//流
private ServerSocket server;//
private Socket socket;//套接字
void getServer(){//此方法完成服务端的各种必要链接
try {
server = new ServerSocket(8997);//实例化Socket对象,并给他个8997端口
System.out.println("服务器套接字创建成功");
while (true){
System.out.println("等待客户端连接");
socket = server.accept();
reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));//实例化BufferedReader对象
getClientMessage();//调用getClientMessage方法
}
}catch (Exception e){
e.printStackTrace();
}
}

private void getClientMessage(){//此方法持续收听客户端信息
try {
while (true){
System.out.println("客户机:" + reader.readLine());//获取客户端信息
}
}catch (Exception e){
e.printStackTrace();
}

try {
if (reader != null){
reader.close();//关闭流
}
if (socket != null){
socket.close();//关闭套接字
}
}catch (IOException e){
e.printStackTrace();
}

}
public static void main(String[] args) {
// write your code here
Main ma = new Main();
ma.getServer();
}
}


 

客户端



package com.company;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.PrintWriter;
import java.net.Socket;

public class users extends JFrame {
private PrintWriter writer;
Socket socket;//创建字节套对象
private JTextArea ta = new JTextArea();
private JTextField tf = new JTextField();
Container cc;
public users(String title){//设置jframe窗体,不是特别重要
super(title);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
cc = this.getContentPane();
final JScrollPane scrollPane = new JScrollPane();
getContentPane().add(scrollPane,BorderLayout.CENTER);
scrollPane.setViewportView(ta);
cc.add(tf,"South");


tf.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
writer.println(tf.getText());//写入流,服务器那边是读取流
ta.append(tf.getText() + "\n");//把文本框信息写在文本域zon
ta.setSelectionEnd(ta.getText().length());
tf.setText("");
}
});
}
private void connect(){//连接服务端
ta.append("尝试链接\n");
try {
socket = new Socket("127.0.0.1",8997);//连接本地服务器,并指定与服务器相同的端口
writer = new PrintWriter(socket.getOutputStream(),true);//打印内容到控制台
ta.append("完成连接\n");

}catch (Exception e){
e.printStackTrace();
}
}

public static void main(String[] args) {
users mm = new users("客户端");
mm.setSize(400,200);
mm.setVisible(true);
mm.connect();
}
}