用Socket建立个最简单的聊天程序

用Socket建立个最简单的聊天程序

Java、Socket、网络编程、聊天

/*一个作为Server*/
import java.io.*;
import java.net.*;
public class MyServer{
 public static void main(String[] args)
      throws IOException{
  ServerSocket s=new ServerSocket(8658);
  System.out.println("开始:"+s);
  try{
   Socket socket=s.accept();
   try{
    System.out.println("连接接受"+socket);
    BufferedReader in=new BufferedReader(new InputStreamReader
      (socket.getInputStream()));
    PrintWriter out=new PrintWriter(new BufferedWriter(
     new OutputStreamWriter(socket.getOutputStream())),true);
    while(true){
     String str=in.readLine();
     if(str.equals("q")) break;
     System.out.println("对方说:"+str);
     BufferedReader is=new BufferedReader(new InputStreamReader(System.in));
     String input=new String();
     input=is.readLine().trim();
     out.println(input);
     System.out.print("我说:");
     out.flush();
    }
   }
   finally{
    System.out.println("关闭....");
    socket.close();
   }
  }
  finally{
   s.close();
  }
 }
}

/*一个作为Client*/
import java.io.*;
import java.net.*;
public class MyClient{
 public static void main(String[] args)
   throws IOException{
  InetAddress addr=InetAddress.getByName("127.0.0.1");
  System.out.println("地址="+addr);
  Socket socket=new Socket(addr,8658);
  try{
   System.out.println("socket="+socket);
   BufferedReader is=new BufferedReader(new InputStreamReader(System.in));
    PrintWriter out=new PrintWriter(socket.getOutputStream(),true);
   for(;;){
    System.out.print("我说:");
    String input=new String();
    input=is.readLine().trim();
    out.println(input);
    if(input.equals("q")) break;
    BufferedReader in=new BufferedReader(new InputStreamReader
        (socket.getInputStream()));
     String str=in.readLine();
    System.out.println("对方说:"+str);
    out.flush();
   }

  }
  finally{
   System.out.println("关闭");
   socket.close();
  }
 }
}

阅读更多
想对作者说点什么? 我来说一句

C++编写的Socket聊天程序源代码

2009年04月27日 239KB 下载

没有更多推荐了,返回首页

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭