最近复习了下TCP,写了个聊天demo
服务端:
import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.net.ServerSocket; import java.net.Socket; import java.util.Scanner; public class TcpService { static OutputStream os =null; static InputStream is=null; static Socket socket = null; static ServerSocket serverSocket = null; public static void main(String[] args) { Scanner cin = new Scanner (System.in); try { System.out.println("服务器启动"); //构造ServerSocket实例,指定端口监听客户端的连接请求 serverSocket = new ServerSocket(8080); // 建立跟客户端的连接 socket = serverSocket.accept(); // 向客户端发送消息 is = socket.getInputStream(); os = socket.getOutputStream(); InputStreamReader isr=new InputStreamReader(is,"utf-8"); OutputStreamWriter osw = new OutputStreamWriter(os,"utf-8"); //osw.write(msg); // 接受客户端的响应 new Thread() { public void run() { // TODO Auto-generated method stub while (true) { //byte b[] = new byte[1024]; char[] cha=new char[1024]; int len=0; try { len = isr.read(cha); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("小明说:"+new String(cha,0,len)); } } }.start(); //向客户端发送消息 new Thread(){ public void run(){ // TODO Auto-generated method stub while(cin.hasNext()){ String str=cin.next(); try { //osw.write(str); os.write(str.getBytes()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }.start(); } catch (IOException e) { e.printStackTrace(); } finally { } } }
客户端:
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.net.Socket; import java.util.Scanner; public class test { static Socket socket = null; static InputStream is = null; static OutputStream os = null; public static void main(String[] args) { Scanner cin = new Scanner (System.in); try { // 对服务端发起连接请求 System.out.println("已经连接服务器"); socket = new Socket("localhost", 8080); is = socket.getInputStream(); os = socket.getOutputStream(); InputStreamReader isr=new InputStreamReader(is,"GBK"); OutputStreamWriter osw = new OutputStreamWriter(os,"GBK"); os.write("已经接服务器。".getBytes()); //接收服务器信息 new Thread() { public void run() { // TODO Auto-generated method stub while (true) { //byte b[] = new byte[1024]; char[] cha=new char[1024]; int len=0; try { len = isr.read(cha); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("小红说:"+new String(cha,0,len)); } } }.start(); // 给服务端发送响应信息 new Thread(){ public void run(){ // TODO Auto-generated method stub while(cin.hasNext()){ String str=cin.next(); try { //osw.write(str); os.write(str.getBytes()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }.start(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
效果图: