Socket程序,server启动,可以有多个线程向server发送信息,server收到信息后,在信息前加上“ECHO”并将内容转为大写返回。当发送“byebye”时,通信结束,关闭客户端。
serverSocket代码:
package server;
import java.io.IOException;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
public class SocketServer {
private static class Mythread implements Runnable{
private Socket client;
public Mythread(Socket client) {
this.client = client;
}
@Override
public void run() {
try {
Scanner scanner = new Scanner(client.getInputStream()); // 接收客户端发来的数据。
scanner.useDelimiter("\r\n");
PrintStream out = new PrintStream(client.getOutputStream()); //向客户端发送消息
boolean flag = true;
while(flag) {
if(scanner.hasNext()) {
String str = scanner.next().trim();//防止有多余的空格
System.out.println("收到一条信息");
if ("byebye".equalsIgnoreCase(str)) {
flag = false;
break;
}
out.println("ECHO : " + str.toUpperCase());
}
}
scanner.close();
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static void main(String[] args) throws IOException {
ServerSocket server = new ServerSocket(9999); //监听端口
System.out.println("启动成功");
boolean flag = true;
while(flag) {
Socket client = server.accept();//接收连接
new Thread(new Mythread(client)).start();
}
server.close();
}
}
客户端代码:
package client;
import java.io.PrintStream;
import java.net.Socket;
import java.util.Scanner;
public class Client {
public static void main(String[] args) throws Exception {
Socket client = new Socket("127.0.0.1", 9999); //与127.0.0.1的主机的9999端口建立连接
Scanner keyScanner = new Scanner(System.in); // 键盘输入
keyScanner.useDelimiter("\r\n");
Scanner netScanner = new Scanner(client.getInputStream()); //用于读取socket返回的内容
netScanner.useDelimiter("\r\n");
PrintStream netout = new PrintStream(client.getOutputStream()); //发送键盘内容给server
boolean flag = true;
while(flag) {
System.out.println("请输入要发送的字符:");
if (keyScanner.hasNext()) {
String str = keyScanner.next().trim();
netout.println(str);
if (netScanner.hasNext()) {
System.out.println(netScanner.next() );
}
if ("byebye".equalsIgnoreCase(str)) {
flag = false;
break;
}
}
}
keyScanner.close();
netScanner.close();
netout.close();
client.close();
}
}