服務器端
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
//點對點聊天程序
public class Myserver implements Runnable{
ServerSocket server =null;
Socket clientSocket; //負責當前線程中c/s通信中的Socket對象
boolean flag = true; //標記是否結束
Thread connenThread; //向客戶端發送信息的線程
BufferedReader sin; //輸入流對象
DataOutputStream sout; //輸出流對象
public static void main(String[] args) {
Myserver myserver=new Myserver();
myserver.serverStart();
}
public void serverStart()
{
try {
server=new ServerSocket(8080); //建立監聽服務
System.out.println("端口號:"+server.getLocalPort());
while (flag){
clientSocket=server.accept();
System.out.println("連接已經建立完畢!");
InputStream is=clientSocket.getInputStream();
sin=new BufferedReader(new InputStreamReader(is));
OutputStream os=clientSocket.getOutputStream();
sout=new DataOutputStream(os);
connenThread =new Thread(this);
connenThread.start(); //啟動線程向客戶端發送信息
String aLine;
while ((aLine=sin.readLine())!=null)
{
System.out.println(aLine);
if(aLine.equals("bye")){
flag=false;
connenThread.interrupt();
break;
}
}
sout.close();
os.close();
sin.close();
is.close();
clientSocket.close();
System.exit(0);
}
} catch (IOException e) {
e.printStackTrace();
}
}
public void run(){
while(true){
try {
int ch;
while((ch=System.in.read())!=-1)
{
sout.write((byte) ch); //從鍵盤接受字符並向客戶端發送
if(ch=='\n')
sout.flush(); //將緩沖區內容向客戶端輸出
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void finalize(){
try {
server.close(); //停止ServerSocket服務
} catch (IOException e) {
e.printStackTrace();
}
} //析構方法
}
客戶端
import java.io.*;
import java.net.Socket;
public class MyClient implements Runnable{
Socket clientSocket;
boolean flag=true;
Thread connenThread; //向服務器發送消息
BufferedReader cin;
DataOutputStream cout;
public static void main(String[] args) {
new MyClient().clientStart();
}
public void clientStart(){
try {
clientSocket=new Socket("localhost",8080); //這是本機連接
System.out.println("已建立連接");
while (flag){
InputStream is=clientSocket.getInputStream();
cin=new BufferedReader(new InputStreamReader(is));
OutputStream os=clientSocket.getOutputStream();
cout=new DataOutputStream(os);
connenThread=new Thread(this);
connenThread.start(); //啟動線程,向服務器發送信息
String aLine;
while ((aLine=cin.readLine())!=null){ //接收服務器端的數據
System.out.println(aLine);
if (aLine.equals("bye")){
flag=false;
connenThread.interrupt();
break;
}
}
cout.close();
os.close();
cin.close();
is.close();
clientSocket.close(); //關閉Socket連接
System.exit(0);
}
} catch (IOException e) {
e.printStackTrace();
}
}
public void run(){
while (true){
int ch;
try {
while((ch=System.in.read())!=-1){ //從鍵盤接收字符並向服務器發送
cout.write((byte)ch);
if(ch=='\n'){
cout.flush(); //將緩沖區內容向輸出流發送
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}