客户端代码展示
import javax
.swing
.*;
import java
.awt
.*;
import java
.io
.*;
import java
.net
.Socket
;
import java
.util
.Scanner
;
public class TCPClient {
static JFrame jf
= new JFrame("客户端");
static JButton jb
= new JButton("发送");
static JPanel pane
= new JPanel(new FlowLayout());
static JTextArea jta
= new JTextArea(50,40);
static JTextField jtf
= new JTextField(20);
public static void init(){
pane
.add(jta
);
pane
.add(jtf
);
pane
.add(jb
);
jf
.setContentPane(pane
);
jf
.pack();
jf
.setDefaultCloseOperation(WindowConstants
.EXIT_ON_CLOSE);
jf
.setVisible(true);
}
public static void main(String
[] args
) throws Exception
{
new TCPClient().init();
final Socket
[] socket
= {null};
jb
.addActionListener((event
)->{
new Thread(new Runnable() {
@Override
public void run() {
try{
socket
[0] =new Socket("127.0.0.1",9090);
PrintStream ps
=new PrintStream(new BufferedOutputStream(socket
[0].getOutputStream()));
System
.out
.println("请输入内容:");
String str
= jtf
.getText();
ps
.println(str
);
ps
.flush();
jtf
.setText("");
jta
.append("我的信息:"+str
+"\n");
Thread
.sleep(200);
BufferedReader br
=new BufferedReader(new InputStreamReader(socket
[0].getInputStream(),"utf-8"));
String info
=br
.readLine();
if (info
!=null || "".equals(info
)){
String string
=new String(info
.getBytes("utf-8"));
jta
.append("服务器信息:"+string
+"\n");
}
socket
[0].close();
}catch (Exception ex
){
ex
.printStackTrace();
}
}
}).start();
});
}
}
客户端运行界面:
服务器代码展示:
public class TCPServer {
static JFrame jf
= new JFrame("服务器端");
static JButton jb
= new JButton("发送");
static JPanel pane
= new JPanel(new FlowLayout());
static JTextArea jta
= new JTextArea(10,20);
static JTextField jtf
= new JTextField(12);
public static void init(){
pane
.add(jta
);
pane
.add(jtf
);
pane
.add(jb
);
jf
.setContentPane(pane
);
jf
.pack();
jf
.setDefaultCloseOperation(WindowConstants
.EXIT_ON_CLOSE);
jf
.setVisible(true);
}
public static void main(String
[] args
)throws Exception
{
ServerSocket serverSocket
= new ServerSocket(9090);
System
.out
.println("服务器已经启动,等待客户端连接");
Socket socket
= null;
while(true){
socket
= serverSocket
.accept();
try{
BufferedReader br
= new BufferedReader(new InputStreamReader(socket
.getInputStream(),"utf-8"));
String str
= br
.readLine();
if (str
==null||"".equals(str
)){
}
else {
System
.out
.println("接受到客户端的消息:");
System
.out
.println(str
);
PrintStream ps
=new PrintStream(new BufferedOutputStream(socket
.getOutputStream()));
Scanner input
= new Scanner(System
.in);
System
.out
.println("请输入你的信息:");
String str1
= input
.next();
ps
.println(new String(str1
.getBytes("utf-8")));
ps
.flush();
}
}catch (Exception ex
){
ex
.printStackTrace();
}finally {
socket
.close();
}
}
}
}
总体运行结果: 总结:该代码样例仅仅能够用于客户端和服务器端进行一问一答式的交互。 存在问题:问题主要存在于两方面: 1、在服务器端上,可以根据自身的情况需求使用界面代码自己去创建窗口。 2、在服务器向我发送中文字符"。"时,出现乱码问题,但是其他字符并没有出现异常情况。 最后,这是本人的第一篇博客,希望大家可以批评指正,共同进步,谢谢!