简单的网络通讯小程序
作者:
腾杨天下
,
2021-07-18 23:32:49
,
所有人可见
,
阅读 386
简单的网络通讯小程序
package socket;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;
public class MyServer {
public static final int MY_SERVER_PORT = 12727;
public static final Charset MY_COMM_CHARSET = StandardCharsets.UTF_8;
public static final String BYE = "bye";
public static void main(String[] args) throws IOException {
commWithClient();
}
private static void commWithClient() throws IOException {
try (
ServerSocket ss = new ServerSocket(MY_SERVER_PORT);
Socket s = ss.accept();
) {
MyChat myChat=new MyChat("客户端","你已经连接上服务器了",s);
myChat.chatting();
}
}
package socket;
import java.io.IOException;
import java.net.Socket;
import static socket.MyServer.MY_SERVER_PORT;
public class MyClient {
public static void main(String[] args) {
commWithServer();
}
private static void commWithServer() {
try (
Socket s=new Socket("localhost",MY_SERVER_PORT);
){
// System.out.println("客户端连接到:"+s.getRemoteSocketAddress());
MyChat myChat=new MyChat("服务器端",null,s);
myChat.chatting();
} catch (IOException e) {
e.printStackTrace();
}
}
}
package socket;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import static socket.MyServer.BYE;
import static socket.MyServer.MY_COMM_CHARSET;
public class MyChat {
private String from;
private String greeting;
private Socket s;
public MyChat(String from, String greeting, Socket s) {
this.from = from;
this.greeting = greeting;
this.s = s;
}
public void chatting() {
Scanner in = new Scanner(System.in);
try (
BufferedReader br = new BufferedReader(
new InputStreamReader(s.getInputStream(), MY_COMM_CHARSET));
PrintWriter pw = new PrintWriter(
new OutputStreamWriter(s.getOutputStream(), MY_COMM_CHARSET));
) {
if(greeting!=null) {
pw.println(greeting);
pw.flush();
}
while (true) {
String line = br.readLine();
if (line.equalsIgnoreCase(BYE)) {
pw.println(BYE);
break;
} else {
System.out.println(from+":" + line);
String myword = in.nextLine();
pw.println(myword);
pw.flush();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}