网络编程 编程聊天小程序

第一

package zdian;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.util.Scanner;
public class ServerTest {
 public static void main(String[] args) {
  Scanner sc = new Scanner(System.in);
  try {
   Socket c = new Socket("192.168.0.116",5928);
   System.out.print("请输入:");
   String name =sc.nextLine();
   OutputStream os = c.getOutputStream();
   String info = String.format("我是:%s, 我的IP是:%s.\r\n",name,InetAddress.getLocalHost());
  // InputStream is =  c.getInputStream();
   os.write(info.getBytes("utf-8"));
   InputStream is =c.getInputStream();
   byte[] buf =new byte[1024];
   is.read(buf);
   System.out.println(new String(buf,"utf-8"));
   os.flush();
   is.close();
   os.close();
  } catch (IOException e) {
   
   e.printStackTrace();
 }
 }
}
第2
package zdian;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class Socker {
 public static void main(String[] args) {
  ServerSocket s;
  try {
   s = new ServerSocket(5928);
   Socket server = s.accept();
   //System.out.println("有人访问.");
   InputStream is =server.getInputStream();
   byte[] buf =new byte[1024];
   is.read(buf);
   System.out.println(new String(buf,"utf-8"));
   
   OutputStream os = server.getOutputStream();
   os.write("欢迎你!\r\n".getBytes("utf-8"));
   os.flush();
   is.close();
   os.close();
  // os.close();
  } catch (IOException e) {
   
   e.printStackTrace();
  }
  
 }
}
posted @ 2020-06-16 20:38  信王勤宝  阅读(158)  评论(0编辑  收藏  举报