本帖最后由 徐壹 于 2018-12-20 08:44 编辑
局域网「点对点」聊天工具客户端:[Java] 纯文本查看 复制代码 import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Scanner;
/**
* @Author:hr947x
* @Date:2018/12/19 11:44
* @version:1.0
*/
public class Client {
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
System.out.println("请输入你的名字:");
String name = s.nextLine();
System.out.println("等待连接服务器...");
Socket s = new Socket("127.0.0.1", 13579);
OutputStream ops = s.getOutputStream();
String getMessage = "";
ops.write(name + "连接成功!".getBytes());
// 接收消息线程
new Thread(()->{try {
while (true) {
InputStream ips = s.getInputStream();
byte[] bytes = new byte[1024];
int len = -1;
len = ips.read(bytes);
System.out.println(new String(bytes, 0, len));
}
} catch (IOException e) {
e.printStackTrace();
}}).start();
// 死循环发送消息
while (true) {
ops.write((name + ":" + sc.nextLine()).getBytes());
}
}
}
服务器端:
[Java] 纯文本查看 复制代码 import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
/**
* @Author:hr947x
* @Date:2018/12/19 11:44
* @version:1.0
*/
public class Server {
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
System.out.println("请输入你的名字:");
String name = s.nextLine();
System.out.println("等待客户端连接...");
ServerSocket ss = new ServerSocket(13579);
Socket s = ss.accept();
OutputStream os = s.getOutputStream();
os.write(name + "连接成功!".getBytes());
// 接收消息线程
new Thread(() -> {
try {
while (true) {
InputStream is = s.getInputStream();
byte[] bytes = new byte[1024];
int len = -1;
len = is.read(bytes);
System.out.println(new String(bytes, 0, len));
}
} catch (IOException e) {
e.printStackTrace();
}
}).start();
// 死循环发送消息
while (true) {
os.write((name + ":" + sc.nextLine()).getBytes());
}
}
}
|