java套接字
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
public class ServerSocket {
public static void main(String[] args) throws IOException{
ServerSocket ss = new ServerSocket(8888);
Socket s = null;
while(true) {
s = ss.accept();
System.out.println(s.getPort()+""+s.getInetAddress()+"上线了");
BufferedReader bf = new BufferedReader(new InputStreamReader(s.getInputStream()));
PrintWriter pw = new PrintWriter(s.getOutputStream(),true);
String str;
boolean a = true;
while((str = bf.readLine())!= null) {
System.out.println(str);
if(str.equals("bye")) {
pw.println("disconnect");
System.out.println(s.getPort()+""+s.getInetAddress()+"下线了");
a = false;
break;
}
pw.println("我已收到"+str);
}
if(!a) {
break;
}
}
}
}
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
public class client {
public static void main(String[] args) throws UnknownHostException, IOException {
// TODO Auto-generated method stub
Socket s = new Socket("127.0.0.1", 8888);
BufferedReader bf = new BufferedReader(new InputStreamReader(s.getInputStream()));
PrintWriter pw = new PrintWriter(s.getOutputStream(),true);
BufferedReader standin = new BufferedReader(new InputStreamReader(System.in));
String str;
while((str = standin.readLine()) != null) {
pw.println(str);
String str2;
str2 = bf.readLine();
System.out.println(str2);
if(str2.equals("disconnect")) {
break;
}
}
}
}