import java.io.IOException;
import java.io.InputStream;
import java.net.*;
import java.util.Scanner;
public class Domefuwu { //服务端
static Scanner sc = new Scanner(System.in);
static Socket socket = null;
static ServerSocket sever = null;
public static void main(String[] args) {
System.out.println("已经建立服务器");
try {
sever = new ServerSocket(7878); //新建一个端口,名为sever:7878
while(true){
socket = sever.accept(); //监视端口sever
System.out.println("已经和"+socket.getLocalAddress()+"建立聊天通道\n等待对方发言");
duqu(); //调用读取方法
}
} catch (Exception e) {
e.printStackTrace();
}
}
private static void duqu() throws IOException { //定义读取方法
InputStream input = socket.getInputStream();
byte[] bytes = new byte[1024];
int len = 0;
StringBuffer buffer = new StringBuffer();
while((len = input.read(bytes)) != -1){
buffer.append(new String(bytes,0,len));
}
input.close();
System.out.println("对方发来消息"+buffer.toString()); //将读取到的消息输出
}
}
package duankou;
import java.io.*;
import java.net.*;
import java.util.*;
public class Domekehu { //客户端
static Scanner sc = new Scanner(System.in);
static Socket socket = null;
public static void main(String[] args) throws Exception {
System.out.println("客户端正在尝试连接");
try {
socket = new Socket("127.0.0.1",7878); //链接端口:7878
try {
fayan(); //调用发言方法
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
}
private static void fayan() throws Exception { //定义发言方法
System.out.println("链接成功,请发言");
String nei = sc.next(); //输入并传输给服务端
OutputStream output = socket.getOutputStream();
output.write(nei.getBytes());
output.close();
}
}