用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();
}
}
}
本文地址:http://com.8s8s.com/it/it11149.htm