ThreadServer.java
import java.io.*;
import java.net.*;
/**
*
* @author heqichang
* 服务端接收信息线程
* */
public class ThreadServer extends Thread{
Socket serverSocket;
public void run()
{
try {
BufferedReader br=new BufferedReader(new InputStreamReader(serverSocket.getInputStream()));
String read=new String();
//接受客户端的姓名信息
String name=br.readLine();
//循环接受客户端信息
while(true)
{
read=br.readLine();
System.out.println(name+"说:"+read);
if(read.equals("bye"))
{
break;
}
}
br.close();
serverSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public ThreadServer(Socket server)
{
serverSocket=server;
}
}
ThreadSocketClient.java
import java.io.*;
import java.net.*;
/**
*
*
* 客户端
* */
public class ThreadSocketClient extends Thread{
static Socket socket;
public void run()
{
try {
BufferedReader br2=new BufferedReader(new InputStreamReader(socket.getInputStream()));
String read=new String();
//接受来自服务端的姓名信息
String name=br2.readLine();
//接受来自服务端的信息
while(true)
{
read=br2.readLine();
System.out.println(name+"说:"+read);
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws IOException
{
socket=new Socket("127.0.0.1",9999);
BufferedReader inputName=new BufferedReader(new InputStreamReader(System.in));
System.out.print("已连接上服务端,请输入你的姓名:");
String name=inputName.readLine();
//启动一个线程进行接收服务端信息
ThreadSocketClient thread=new ThreadSocketClient();
thread.start();
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
PrintWriter pw=new PrintWriter(socket.getOutputStream());
//发送给服务端客户端的姓名信息
pw.println(name);
String info=new String();
//发送消息给服务端
while(!info.equals("bye"))
{
info=br.readLine();
pw.println(info);
pw.flush();
}
pw.close();
socket.close();
}
}
ThreadSocketServer.java
import java.io.*;
import java.net.*;
import javax.swing.JOptionPane;
/**
*
* @author bruceli
* 服务端
* */
public class ThreadSocketServer extends Thread {
Socket server;
//保存服务端的姓名
static String name = new String();
public void run() {
try {
//启动一个线程来接收客户端信息
ThreadServer thread = new ThreadServer(server);
thread.start();
BufferedReader br = new BufferedReader(new InputStreamReader(
System.in));
PrintWriter pw = new PrintWriter(server.getOutputStream());
//第一次发送自己的姓名给客户端
pw.println(name);
//循环发送信息给客户端
while (true) {
String s = br.readLine();
pw.println(s);
pw.flush();
}
} catch (IOException e) {
e.printStackTrace();
}
}
public ThreadSocketServer(Socket s) {
this.server = s;
}
public static void main(String[] args) throws IOException {
//绑定服务端在9999端口
ServerSocket server = new ServerSocket(9999);
Socket socket;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("请输入您的姓名:");
name = br.readLine();
while (true) {
//监听客户端程序
socket = server.accept();
//一个客户端连接后启动一个线程进行处理
ThreadSocketServer thread = new ThreadSocketServer(socket);
thread.start();
JOptionPane.showMessageDialog(null,"有客户端连接到了9999端口");
}
}
}
执行效果: