package test;
import java.io.*;
import java.net.*;
import java.util.Scanner;
public class Client
{
private Socket socket = null;
private class ReceiveThread extends Thread
{
@Override
public void run()
{
while (true)
{
try
{
DataInputStream dis = new DataInputStream(socket.getInputStream());
String receiveMessage = dis.readUTF();
System.out.println("客户端发送消息: " + receiveMessage);
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
}
public void start() throws IOException
{
socket = new Socket(InetAddress.getByName("localhost"), 7788);
new ReceiveThread().start();
System.out.println("已经和服务器建立连接\n请输入你要发送的消息 : ");
while (true)
{
Scanner scaner = new Scanner(System.in);
String message = scaner.next();
DataOutputStream dout = new DataOutputStream(socket.getOutputStream());
dout.writeUTF(message);
dout.flush();
}
}
public static void main(String[] args) throws IOException
{
Client client = new Client();
client.start();
}
}
package test;
import java.io.*;
import java.net.*;
import java.util.*;
public class Server
{
private ServerSocket ss = null;
private List<Socket> list = new LinkedList<Socket>();
private class ReceiveThread extends Thread
{
private Socket socket = null;
public ReceiveThread(Socket socket)
{
this.socket = socket;
}
@Override
public void run()
{
while (true)
{
if (socket == null)
{
continue;
}
try
{
DataInputStream dis = new DataInputStream(socket.getInputStream());
String receiveMessage = dis.readUTF();
System.out.println("收到客户端发送的消息 :" + socket+ " " + receiveMessage);
send(receiveMessage);
} catch (IOException e)
{
e.printStackTrace();
}
}
}
}
public void send(String msg) throws IOException
{
for (int i = 0; i < list.size(); i++)
{
Socket groupSocket = list.get(i);
OutputStream out = groupSocket.getOutputStream();
DataOutputStream dout = new DataOutputStream(out);
dout.writeUTF(msg);
dout.flush();
out.flush();
}
}
private void start() throws IOException
{
ss = new ServerSocket(7788);
while (true)
{
while (true)
{
Socket socket = ss.accept();
list.add(socket);
new ReceiveThread(socket).start();
}
}
}
public static void main(String[] args) throws Exception
{
System.out.println("服务器开启成功");
new Server().start();
}
}