TCP聊天
server
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
public class server {
public static void main(String[] args) throws UnknownHostException, IOException {
ServerSocket server = new ServerSocket(8888);
Socket socket = server.accept();
System.out.println("connected");
String ms=null;
BufferedReader bInputStream = new BufferedReader(new InputStreamReader(socket.getInputStream()));
ms = bInputStream.readLine();
bInputStream.close();
System.out.println(ms);
socket.close();
}
}
client端
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.UnknownHostException;
public class client {
public static void main(String[] args) throws UnknownHostException, IOException {
Socket socket = new Socket("localhost", 8888);
String string = "HelloWorld";
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
bufferedWriter.write(string);
bufferedWriter.newLine();
bufferedWriter.flush();
bufferedWriter.close();
socket.close();
}
}