導航:首頁 > 源碼編譯 > jdksocket源碼

jdksocket源碼

發布時間:2023-01-11 23:38:11

❶ socket java 源代碼

很久以前做的了,啟動程序兩次,在單選框中選伺服器點連接(一定要先點伺服器-連接),在在另外一個界面中選客戶端點連接;

import java.awt.Color;
import java.awt.Container;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Date;

import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JRadioButton;
import javax.swing.JTextArea;
import javax.swing.JTextField;

public class QQ extends JFrame implements ActionListener{
public static void main(String args[]){
QQ qq=new QQ();

}
String input;
ServerSocket ss;
Socket s1,s2;
PrintWriter pw;
BufferedReader br;
private server s;
private client cc;
private JLabel l1,l2,l3,l4,l5;
private JRadioButton jb[]=new JRadioButton[2];
private JTextField jf1,jf2,jf3;
private JButton j1,j2,j3;
private JTextArea ja;
public QQ(){
super("聊天");
Container c=getContentPane();
c.setLayout(null);
l1=new JLabel("TCP通信程序");
l1.setFont(new Font("宋體",Font.BOLD,16));
l1.setBackground(Color.black);
l1.setSize(2000,20);
l1.setLocation(10,10);
c.add(l1);
String str1[]={"服務端","客戶端"};

ButtonGroup bg=new ButtonGroup();
for(int x=0;x<str1.length;x++)
{
jb[x]=new JRadioButton(str1[x]);
jb[x].setFont(new Font("宋體",Font.BOLD,15));
jb[x].setForeground(Color.black);
jb[x].setSize(80,40);
jb[x].setLocation(10+x*80,37);
bg.add(jb[x]);
c.add(jb[x]);
}
jb[0].setSelected(true);

l2=new JLabel("連接主機IP");
l2.setFont(new Font("宋體",Font.BOLD,16));
l2.setBackground(Color.black);
l2.setSize(120,20);
l2.setLocation(20, 80);
c.add(l2);

jf1=new JTextField("127.0.0.1");
jf1.setSize(220,30);
jf1.setLocation(120, 80);
c.add(jf1);

jf3=new JTextField("離線");
jf3.setSize(150,30);
jf3.setLocation(280, 40);
c.add(jf3);

l5=new JLabel("連接狀態:");
l5.setFont(new Font("宋體",Font.BOLD,16));
l5.setBackground(Color.black);
l5.setSize(120,20);
l5.setLocation(200, 47);
c.add(l5);

j1=new JButton("連接");
j1.setSize(110,20);
j1.setLocation(360,85);
j1.addActionListener(this);
c.add(j1);

l3=new JLabel("接收到的信息");
l3.setFont(new Font("宋體",Font.BOLD,16));
l3.setBackground(Color.black);
l3.setSize(120,20);
l3.setLocation(20, 130);
c.add(l3);

ja=new JTextArea();
ja.setSize(250,200);
ja.setLocation(130, 130);
c.add(ja);

l4=new JLabel("發送信息");
l4.setFont(new Font("宋體",Font.BOLD,16));
l4.setBackground(Color.black);
l4.setSize(120,20);
l4.setLocation(20, 340);
c.add(l4);

jf2=new JTextField("gf");
jf2.setSize(220,30);
jf2.setLocation(120, 340);
c.add(jf2);

j2=new JButton("發送信息");
j2.setSize(110,20);
j2.setLocation(360,350);
j2.addActionListener(this);
c.add(j2);

j3=new JButton("結束連接");
j3.setSize(110,20);
j3.setLocation(360,110);
j3.addActionListener(this);
c.add(j3);
s=new server();
cc=new client();
j3.setEnabled(false);
j2.setEnabled(false);

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(500,450);
setVisible(true);
setLocation(300,300);
}

public void actionPerformed(ActionEvent e) {
// TODO 自動生成方法存根

if(e.getSource()==j1)
{
try{
if(jb[0].isSelected()==true)
{
input="";
s.start();
}
else {
input="";
cc.start();
}
}
catch(Exception ee)
{
jf3.setText("發生錯誤");
}
}

if(e.getSource()==j2)
{

pw.write(jf2.getText()+"\n");

pw.flush();

}

if(e.getSource()==j3)
{
try
{
if(jb[0].isSelected()==true)
{ s1.close();
jf3.setText("離線");

j2.setEnabled(false);
j3.setEnabled(false);

}

else
{

s2.close();
jf3.setText("離線");
j2.setEnabled(false);
j3.setEnabled(false);

}
}
catch (Exception e1) {
// TODO 自動生成 catch 塊

}

}

}

class server extends Thread{
public void run(){
try {

j1.setEnabled(false);

jf3.setText("正在連接中@");

ss=new ServerSocket(4000);
s1=ss.accept();

br=new BufferedReader(new InputStreamReader(s1.getInputStream()));
pw=new PrintWriter(s1.getOutputStream(),true);
// bs=new BufferedOutputStream(os);
while(true){
if(ss.isBound()==true){

jf3.setText("連接成功");
j2.setEnabled(true);
j3.setEnabled(true);
break;
}
}
while(true)
{
input=br.readLine();

if(input.length()>0){
ja.append(input);
ja.append("\n");

}

}

} catch (Exception e) {
// TODO 自動生成 catch 塊

}

}

}

class client extends Thread{
public void run(){
try {

j1.setEnabled(false);
jf3.setText("正在連接中@");
s2=new Socket(InetAddress.getByName(jf1.getText()),4000);

// s2=new Socket();
// s2.connect(new InetSocketAddress(jf1.getText(),21),1000);
br=new BufferedReader(new InputStreamReader(s2.getInputStream()));
pw=new PrintWriter(s2.getOutputStream(),true);

// bs=new BufferedOutputStream(os);
while(true){
if(s2.isConnected()==true){
jf3.setText("連接成功");
j2.setEnabled(true);
j3.setEnabled(true);
break;

}

}

input="";
while(true){
input=br.readLine();
if(input.length()>0)
{

ja.append(input);

}
}

} catch (Exception e) {
// TODO 自動生成 catch 塊

}
}

}
}

❷ JAVA Socket 底層是怎樣基於TCP/IP 實現的

首先必須明確:TCP/IP模型中有四層結構:
應用層(Application Layer)、傳輸層(Transport Layer)、網路層(Internet Layer )、鏈路層(LinkLayer)
其中Ip協議(Internet Protocol)是位於網路層的,TCP協議時位於傳輸層的。通過Ip協議可以使可以使兩台計算機使用同一種語言,從而允許Internet上連接不同類型的計算機和不同操作系統的網路。Ip協議只保證計算機能夠接收和發送分組數據。 當計算機要和遠程的計算機建立連接時,TCP協議會讓他們建立連接:用於發送和接收數據的虛擬電路。

在JAVA中,我們用 ServerSocket、Socket類創建一個套接字連接,從套接字得到的結果是一個InputStream以及OutputStream對象,以便將連接作為一個IO流對象對待。通過IO流可以從流中讀取數據或者寫數據到流中,讀寫IO流會有異常IOException產生。

套接字或插座(socket)是一種軟體形 式的抽象,用於表達兩台機器間一個連接的「終端」。針對一個特定的連接,每台機器上都有一個「套接字」,可以想像它們之間有一條虛擬的「線纜」。JAVA 有兩個基於數據流的套接字類:ServerSocket,伺服器用它「偵聽」進入的連接;Socket,客戶端用它初始一次連接。偵聽套接字只能接收新的 連接請求,不能接收實際的數據包,即ServerSocket不能接收實際的數據包。
套接字是基於TCP/IP實現的,它是用來提供一個訪問TCP的服務介面,或者說套接字socket是TCP的應用編程介面API,通過它應用層就可以訪問TCP提供的服務。
在JAVA中,我們用 ServerSocket、Socket類創建一個套接字連接,從套接字得到的結果是一個InputStream以及OutputStream對象,以便 將連接作為一個IO流對象對待。通過IO流可以從流中讀取數據或者寫數據到流中,讀寫IO流會有異常IOException產生。

❸ eclipse怎麼看jdk中源代碼change attached source也找不到

你要選擇jdk安裝目錄下的src.zip這個安裝包才可以, 可以的, 另外就是這個些必須是jdk裡面有的才能看到

❹ java socket技術 客戶端實現不發送請求給服務端但是一直接收服務端發來的數據

說點潑冷水的話題
首先確認什麼是客戶端,什麼是服務端。
從用戶的角度,可見的、可操作的即是客戶端,也就是你這里說的java開發的部分。而不可見的部分就是服務端,也就是你說的C部分。
而從網路開發的角度,發起請求的是客戶端,而接收請求的是服務端。這與用戶感受有很大區別。
當從java請求C的時候,java是客戶端,C 是服務端。而當C主動請求時,則C就變成了客戶端,而java 變成了服務端。
所以,從網路開發的角度,java想成為此次通信的服務端,必須長期維護一個埠可用,而C 要訪問這個埠。
而java為了能夠長期維護一個埠,一般採用socket 方式(其他方式也基本上都是基於socket的),由於java已經封裝的很好了,只要new Socket(IP,port) 就可以 獲得,同時,由於原來C 是伺服器,而如果沒有多個伺服器同時向java端發送請求的話,基本連線程處理都不需要做的。

❺ java 聊天室 源代碼

最簡單的聊天室

❻ 在Android端使用socket傳輸圖片到java伺服器,求源代碼

/**
*思想:
1.直接將所有數據安裝位元組數組發送
2.對象序列化方式
*/

/**
*thread方式
*
*@authorAdministrator
*/
{
privatestaticfinalintFINISH=0;
privateButtonsend=null;
privateTextViewinfo=null;
privateHandlermyHandler=newHandler(){
@Override
publicvoidhandleMessage(Messagemsg){
switch(msg.what){
caseFINISH:
Stringresult=msg.obj.toString();//取出數據
if("true".equals(result)){
TestSocketActivity4.this.info.setText("操作成功!");
}else{
TestSocketActivity4.this.info.setText("操作失敗!");
}
break;
}
}
};


@Override
publicvoidonCreate(BundlesavedInstanceState){
super.onCreate(savedInstanceState);
super.setContentView(R.layout.activity_test_sokect_activity4);
//StrictMode.setThreadPolicy(newStrictMode.ThreadPolicy.Builder()
//.detectDiskReads().detectDiskWrites().detectNetwork()
//.penaltyLog().build());
//StrictMode.setVmPolicy(newStrictMode.VmPolicy.Builder()
//.detectLeakedSqlLiteObjects().detectLeakedClosableObjects()
//.penaltyLog().penaltyDeath().build());

this.send=(Button)super.findViewById(R.id.send);
this.info=(TextView)super.findViewById(R.id.info);
this.send.setOnClickListener(newSendOnClickListener());
}

{
@Override
publicvoidonClick(Viewv){
try{
newThread(newRunnable(){
@Override
publicvoidrun(){
try{
//1:
Socketclient=newSocket("192.168.1.165",9898);
//2:
ObjectOutputStreamoos=newObjectOutputStream(
client.getOutputStream());
//3:
UploadFilemyFile=SendOnClickListener.this
.getUploadFile();
//4:
oos.writeObject(myFile);//寫文件對象
//oos.writeObject(null);//避免EOFException
oos.close();


BufferedReaderbuf=newBufferedReader(
newInputStreamReader(client
.getInputStream()));//讀取返回的數據
Stringstr=buf.readLine();//讀取數據
Messagemsg=TestSocketActivity4.this.myHandler
.obtainMessage(FINISH,str);
TestSocketActivity4.this.myHandler.sendMessage(msg);
buf.close();
client.close();
}catch(Exceptione){
Log.i("UploadFile",e.getMessage());
}
}
}).start();
}catch(Exceptione){
e.printStackTrace();
}
}

()throwsException{//包裝了傳送數據
UploadFilemyFile=newUploadFile();
myFile.setTitle("tangcco安卓之Socket的通信");//設置標題
myFile.setMimeType("image/png");//圖片的類型
Filefile=newFile(Environment.getExternalStorageDirectory()
.toString()
+File.separator
+"Pictures"
+File.separator
+"b.png");
InputStreaminput=null;
try{
input=newFileInputStream(file);//從文件中讀取
ByteArrayOutputStreambos=newByteArrayOutputStream();
bytedata[]=newbyte[1024];
intlen=0;
while((len=input.read(data))!=-1){
bos.write(data,0,len);
}
myFile.setContentData(bos.toByteArray());
myFile.setContentLength(file.length());
myFile.setExt("png");
}catch(Exceptione){
throwe;
}finally{
input.close();
}
returnmyFile;
}
}

}{
privateStringtitle;
privatebyte[]contentData;
privateStringmimeType;
privatelongcontentLength;
privateStringext;

publicStringgetTitle(){
returntitle;
}

publicvoidsetTitle(Stringtitle){
this.title=title;
}

publicbyte[]getContentData(){
returncontentData;
}

publicvoidsetContentData(byte[]contentData){
this.contentData=contentData;
}

publicStringgetMimeType(){
returnmimeType;
}

publicvoidsetMimeType(StringmimeType){
this.mimeType=mimeType;
}

publiclonggetContentLength(){
returncontentLength;
}

publicvoidsetContentLength(longcontentLength){
this.contentLength=contentLength;
}

publicStringgetExt(){
returnext;
}

publicvoidsetExt(Stringext){
this.ext=ext;
}

}

下邊是服務端

publicclassMain4{
publicstaticvoidmain(String[]args)throwsException{
ServerSocketserver=newServerSocket(9898);//伺服器端埠
System.out.println("服務啟動........................");
booleanflag=true;//定義標記,可以一直死循環
while(flag){//通過標記判斷循環
newThread(newServerThreadUtil(server.accept())).start();//啟動線程
}
server.close();//關閉伺服器
}
}


{
="D:"+File.separator+"myfile"
+File.separator;//目錄路徑
privateSocketclient=null;
privateUploadFileupload=null;

publicServerThreadUtil(Socketclient){
this.client=client;
System.out.println("新的客戶端連接...");
}

@Override
publicvoidrun(){
try{
ObjectInputStreamois=newObjectInputStream(
client.getInputStream());//反序列化
this.upload=(UploadFile)ois.readObject();//讀取對象//UploadFile需要和客戶端傳遞過來的包名類名相同,如果不同則會報異常
System.out.println("文件標題:"+this.upload.getTitle());
System.out.println("文件類型:"+this.upload.getMimeType());
System.out.println("文件大小:"+this.upload.getContentLength());

PrintStreamout=newPrintStream(this.client.getOutputStream());//BufferedWriter
out.print(this.saveFile());//返回響應
// BufferedWriterwriter=null;
// writer.write("");
}catch(Exceptione){
e.printStackTrace();
}finally{
try{
this.client.close();
}catch(IOExceptione){
e.printStackTrace();
}
}
}

privatebooleansaveFile()throwsException{//負責文件內容的保存
/**
*java.util.UUID.randomUUID():
*UUID.randomUUID().toString()是javaJDK提供的一個自動生成主鍵的方法。UUID(Universally
*UniqueIdentifier)全局唯一標識符,是指在一台機器上生成的數字,它保證對在同一時空中的所有機器都是唯一的,
*是由一個十六位的數字組成
*,表現出來的形式。由以下幾部分的組合:當前日期和時間(UUID的第一個部分與時間有關,如果你在生成一個UUID之後,
*過幾秒又生成一個UUID,
*則第一個部分不同,其餘相同),時鍾序列,全局唯一的IEEE機器識別號(如果有網卡,從網卡獲得,沒有網卡以其他方式獲得
*),UUID的唯一缺陷在於生成的結果串會比較長,字元串長度為36。
*
*UUID.randomUUID().toString()是javaJDK提供的一個自動生成主鍵的方法。UUID(Universally
*UniqueIdentifier)全局唯一標識符,是指在一台機器上生成的數字,它保證對在同一時空中的所有機器都是唯一的,
*是由一個十六位的數字組成,表現出來的形式
*/
Filefile=newFile(DIRPATH+UUID.randomUUID()+"."
+this.upload.getExt());
if(!file.getParentFile().exists()){
file.getParentFile().mkdir();
}
OutputStreamoutput=null;
try{
output=newFileOutputStream(file);
output.write(this.upload.getContentData());
returntrue;
}catch(Exceptione){
throwe;
}finally{
output.close();
}
}
}{
privateStringtitle;
privatebyte[]contentData;
privateStringmimeType;
privatelongcontentLength;
privateStringext;

publicStringgetTitle(){
returntitle;
}

publicvoidsetTitle(Stringtitle){
this.title=title;
}

publicbyte[]getContentData(){
returncontentData;
}

publicvoidsetContentData(byte[]contentData){
this.contentData=contentData;
}

publicStringgetMimeType(){
returnmimeType;
}

publicvoidsetMimeType(StringmimeType){
this.mimeType=mimeType;
}

publiclonggetContentLength(){
returncontentLength;
}

publicvoidsetContentLength(longcontentLength){
this.contentLength=contentLength;
}

publicStringgetExt(){
returnext;
}

publicvoidsetExt(Stringext){
this.ext=ext;
}

}

❼ 求java網路聊天室(B/S模式)程序代碼

共四個java文件,源代碼如下:

import java.awt.*;
import java.net.*;
import java.awt.event.*;
import java.io.*;
import java.util.Hashtable;

public class ChatArea extends Panel implements ActionListener,Runnable
{
Socket socket=null;
DataInputStream in=null;
DataOutputStream out=null;
Thread threadMessage=null;
TextArea 談話顯示區,私聊顯示區=null;
TextField 送出信息=null;
Button 確定,刷新談話區,刷新私聊區;
Label 提示條=null;
String name=null;
Hashtable listTable;
List listComponent=null;
Choice privateChatList;
int width,height;
public ChatArea(String name,Hashtable listTable,int width,int height)
{
setLayout(null);
setBackground(Color.orange);
this.width=width;
this.height=height;
setSize(width,height);
this.listTable=listTable;
this.name=name;
threadMessage=new Thread(this);
談話顯示區=new TextArea(10,10);
私聊顯示區=new TextArea(10,10);
確定=new Button("送出信息到:");
刷新談話區=new Button("刷新談話區");
刷新私聊區=new Button("刷新私聊區");
提示條=new Label("雙擊聊天者可私聊",Label.CENTER);
送出信息=new TextField(28);
確定.addActionListener(this);
送出信息.addActionListener(this);
刷新談話區.addActionListener(this);
刷新私聊區.addActionListener(this);
listComponent=new List();
listComponent.addActionListener(this);
privateChatList=new Choice();
privateChatList.add("大家(*)");
privateChatList.select(0);

add(談話顯示區);
談話顯示區.setBounds(10,10,(width-120)/2,(height-120));
add(私聊顯示區);
私聊顯示區.setBounds(10+(width-120)/2,10,(width-120)/2,(height-120));
add(listComponent);
listComponent.setBounds(10+(width-120),10,100,(height-160));
add(提示條);
提示條.setBounds(10+(width-120),10+(height-160),110,40);
Panel pSouth=new Panel();
pSouth.add(送出信息);
pSouth.add(確定);
pSouth.add(privateChatList);
pSouth.add(刷新談話區);
pSouth.add(刷新私聊區);
add(pSouth);
pSouth.setBounds(10,20+(height-120),width-20,60);

}
public void setName(String s)
{
name=s;
}
public void setSocketConnection(Socket socket,DataInputStream in,DataOutputStream out)
{
this.socket=socket;
this.in=in;
this.out=out;
try
{
threadMessage.start();
}
catch(Exception e)
{
}
}
public void actionPerformed(ActionEvent e)
{

if(e.getSource()==確定||e.getSource()==送出信息)
{
String message="";
String people=privateChatList.getSelectedItem();
people=people.substring(0,people.indexOf("("));
message=送出信息.getText();
if(message.length()>0)
{
try {
if(people.equals("大家"))
{
out.writeUTF("公共聊天內容:"+name+"說:"+message);
}
else
{
out.writeUTF("私人聊天內容:"+name+"悄悄地說:"+message+"#"+people);
}
}
catch(IOException event)
{
}
}
}
else if(e.getSource()==listComponent)
{
privateChatList.insert(listComponent.getSelectedItem(),0);
privateChatList.repaint();
}
else if(e.getSource()==刷新談話區)
{
談話顯示區.setText(null);
}
else if(e.getSource()==刷新私聊區)
{
私聊顯示區.setText(null);
}
}
public void run()
{
while(true)
{
String s=null;
try
{
s=in.readUTF();
if(s.startsWith("聊天內容:"))
{
String content=s.substring(s.indexOf(":")+1);
談話顯示區.append("\n"+content);
}
if(s.startsWith("私人聊天內容:"))
{
String content=s.substring(s.indexOf(":")+1);
私聊顯示區.append("\n"+content);
}
else if(s.startsWith("聊天者:"))
{
String people=s.substring(s.indexOf(":")+1,s.indexOf("性別"));
String sex=s.substring(s.indexOf("性別")+2);

listTable.put(people,people+"("+sex+")");

listComponent.add((String)listTable.get(people));
listComponent.repaint();
}
else if(s.startsWith("用戶離線:"))
{
String awayPeopleName=s.substring(s.indexOf(":")+1);
listComponent.remove((String)listTable.get(awayPeopleName));
listComponent.repaint();
談話顯示區.append("\n"+(String)listTable.get(awayPeopleName)+"離線");
listTable.remove(awayPeopleName);
}
Thread.sleep(5);
}
catch(IOException e)
{
listComponent.removeAll();
listComponent.repaint();
listTable.clear();
談話顯示區.setText("和伺服器的連接已中斷\n必須刷新瀏覽器才能再次聊天");
break;
}
catch(InterruptedException e)
{
}
}
}
}

ChatServer.java

import java.io.*;
import java.net.*;
import java.util.*;
public class ChatServer
{
public static void main(String args[])
{
ServerSocket server=null;
Socket you=null;
Hashtable peopleList;
peopleList=new Hashtable();
while(true)
{
try
{
server=new ServerSocket(6666);
}
catch(IOException e1)
{
System.out.println("正在監聽");
}
try {
you=server.accept();
InetAddress address=you.getInetAddress();
System.out.println("用戶的IP:"+address);

}
catch (IOException e)
{
}
if(you!=null)
{
Server_thread peopleThread=new Server_thread(you,peopleList);
peopleThread.start();
}
else {
continue;
}
}
}
}
class Server_thread extends Thread
{
String name=null,sex=null;
Socket socket=null;
File file=null;
DataOutputStream out=null;
DataInputStream in=null;
Hashtable peopleList=null;
Server_thread(Socket t,Hashtable list)
{
peopleList=list;
socket=t;
try {
in=new DataInputStream(socket.getInputStream());
out=new DataOutputStream(socket.getOutputStream());
}
catch (IOException e)
{
}
}
public void run()
{

while(true)
{ String s=null;
try
{
s=in.readUTF();
if(s.startsWith("姓名:"))
{
name=s.substring(s.indexOf(":")+1,s.indexOf("性別"));
sex=s.substring(s.lastIndexOf(":")+1);

boolean boo=peopleList.containsKey(name);
if(boo==false)
{
peopleList.put(name,this);
out.writeUTF("可以聊天:");
Enumeration enum=peopleList.elements();
while(enum.hasMoreElements())
{
Server_thread th=(Server_thread)enum.nextElement();
th.out.writeUTF("聊天者:"+name+"性別"+sex);

if(th!=this)
{
out.writeUTF("聊天者:"+th.name+"性別"+th.sex);
}
}

}
else
{
out.writeUTF("不可以聊天:");
}
}
else if(s.startsWith("公共聊天內容:"))
{
String message=s.substring(s.indexOf(":")+1);
Enumeration enum=peopleList.elements();
while(enum.hasMoreElements())
{
((Server_thread)enum.nextElement()).out.writeUTF("聊天內容:"+message);
}
}

else if(s.startsWith("用戶離開:"))
{
Enumeration enum=peopleList.elements();
while(enum.hasMoreElements())
{ try
{
Server_thread th=(Server_thread)enum.nextElement();
if(th!=this&&th.isAlive())
{
th.out.writeUTF("用戶離線:"+name);
}
}
catch(IOException eee)
{
}
}
peopleList.remove(name);
socket.close();
System.out.println(name+"用戶離開了");
break;
}
else if(s.startsWith("私人聊天內容:"))
{
String 悄悄話=s.substring(s.indexOf(":")+1,s.indexOf("#"));
String toPeople=s.substring(s.indexOf("#")+1);

Server_thread toThread=(Server_thread)peopleList.get(toPeople);
if(toThread!=null)
{
toThread.out.writeUTF("私人聊天內容:"+悄悄話);
}
else
{
out.writeUTF("私人聊天內容:"+toPeople+"已經離線");
}
}
}
catch(IOException ee)
{
Enumeration enum=peopleList.elements();
while(enum.hasMoreElements())
{ try
{
Server_thread th=(Server_thread)enum.nextElement();
if(th!=this&&th.isAlive())
{
th.out.writeUTF("用戶離線:"+name);
}
}
catch(IOException eee)
{
}
}
peopleList.remove(name);
try
{
socket.close();
}
catch(IOException eee)
{
}

System.out.println(name+"用戶離開了");
break;
}
}
}
}

import java.awt.*;
import java.io.*;
import java.net.*;
import java.applet.*;
import java.util.Hashtable;

ClientChat.java

public class ClientChat extends Applet implements Runnable
{
Socket socket=null;
DataInputStream in=null;
DataOutputStream out=null;
InputNameTextField 用戶提交昵稱界面=null;
ChatArea 用戶聊天界面=null;
Hashtable listTable;
Label 提示條;
Panel north, center;
Thread thread;
public void init()
{
int width=getSize().width;
int height=getSize().height;
listTable=new Hashtable();
setLayout(new BorderLayout());
用戶提交昵稱界面=new InputNameTextField(listTable);
int h=用戶提交昵稱界面.getSize().height;
用戶聊天界面=new ChatArea("",listTable,width,height-(h+5));
用戶聊天界面.setVisible(false);
提示條=new Label("正在連接到伺服器,請稍等...",Label.CENTER);
提示條.setForeground(Color.red);
north=new Panel(new FlowLayout(FlowLayout.LEFT));
center=new Panel();
north.add(用戶提交昵稱界面);
north.add(提示條);
center.add(用戶聊天界面);
add(north,BorderLayout.NORTH);
add(center,BorderLayout.CENTER);
validate();
}
public void start()
{
if(socket!=null&&in!=null&&out!=null)
{ try
{
socket.close();
in.close();
out.close();
用戶聊天界面.setVisible(false);

}
catch(Exception ee)
{
}
}
try
{
socket = new Socket(this.getCodeBase().getHost(), 6666);
in=new DataInputStream(socket.getInputStream());
out=new DataOutputStream(socket.getOutputStream());
}
catch (IOException ee)
{
提示條.setText("連接失敗");
}
if(socket!=null)
{
InetAddress address=socket.getInetAddress();
提示條.setText("連接:"+address+"成功");
用戶提交昵稱界面.setSocketConnection(socket,in,out);
north.validate();
}
if(thread==null)
{
thread=new Thread(this);
thread.start();
}
}

public void stop()
{
try
{
socket.close();
thread=null;
}
catch(IOException e)
{
this.showStatus(e.toString());
}
}
public void run()
{
while(thread!=null)
{
if(用戶提交昵稱界面.get能否聊天()==true)
{
用戶聊天界面.setVisible(true);
用戶聊天界面.setName(用戶提交昵稱界面.getName());
用戶聊天界面.setSocketConnection(socket,in,out);
提示條.setText("祝聊天愉快!");
center.validate();
break;
}
try
{
Thread.sleep(100);
}
catch(Exception e)
{
}
}
}
}

InputNameTextField。java

import java.awt.*;
import java.net.*;
import java.awt.event.*;
import java.io.*;
import java.util.Hashtable;
public class InputNameTextField extends Panel implements ActionListener,Runnable
{
TextField nameFile=null;
String name=null;
Checkbox male=null,female=null;
CheckboxGroup group=null;
Button 進入聊天室=null,退出聊天室=null;
Socket socket=null;
DataInputStream in=null;
DataOutputStream out=null;
Thread thread=null;
boolean 能否聊天=false;
Hashtable listTable;
public InputNameTextField(Hashtable listTable)
{
this.listTable=listTable;
nameFile=new TextField(10);
group=new CheckboxGroup();
male=new Checkbox("男",true,group);
female=new Checkbox("女",false,group);
進入聊天室=new Button("進入");
退出聊天室=new Button("退出");
進入聊天室.addActionListener(this);
退出聊天室.addActionListener(this);
thread=new Thread(this);
add(new Label("昵稱:"));
add(nameFile);
add(male);
add(female);
add(進入聊天室);
add(退出聊天室);
退出聊天室.setEnabled(false);
}
public void set能否聊天(boolean b)
{
能否聊天=b;
}
public boolean get能否聊天()
{
return 能否聊天;
}
public String getName()
{
return name;
}
public void setName(String s)
{
name=s;
}
public void setSocketConnection(Socket socket,DataInputStream in,DataOutputStream out)
{

this.socket=socket;
this.in=in;
this.out=out;
try{
thread.start();
}
catch(Exception e)
{
nameFile.setText(""+e);
}
}
public Socket getSocket()
{
return socket;
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==進入聊天室)
{
退出聊天室.setEnabled(true);
if(能否聊天==true)
{
nameFile.setText("您正在聊天:"+name);
}
else
{
this.setName(nameFile.getText());
String sex=group.getSelectedCheckbox().getLabel();
if(socket!=null&&name!=null)
{
try{
out.writeUTF("姓名:"+name+"性別:"+sex);
}
catch(IOException ee)
{
nameFile.setText("沒有連通伺服器"+ee);
}
}
}
}
if(e.getSource()==退出聊天室)
{
try
{
out.writeUTF("用戶離開:");
}
catch(IOException ee)
{
}
}
}
public void run()
{
String message=null;
while(true)
{
if(in!=null)
{
try
{
message=in.readUTF();
}
catch(IOException e)
{
nameFile.setText("和伺服器斷開"+e);
}
}
if(message.startsWith("可以聊天:"))
{
能否聊天=true;
break;
}
else if(message.startsWith("聊天者:"))
{
String people=message.substring(message.indexOf(":")+1);
listTable.put(people,people);
}
else if(message.startsWith("不可以聊天:"))
{
能否聊天=false;
nameFile.setText("該昵稱已被佔用");
}
}
}
}

閱讀全文

與jdksocket源碼相關的資料

熱點內容
php發送https請求 瀏覽:483
找一本小說主角娶了李富真 瀏覽:415
台灣一類片 瀏覽:452
日本電影小伙重生 瀏覽:919
命令提示符文件夾 瀏覽:936
韓國電影愛情 瀏覽:900
任務管理器打開命令行 瀏覽:861
彼時曾相伴電影努努 瀏覽:534
主角重生民國參加黃埔 瀏覽:414
睿威仕無線攝像用什麼app 瀏覽:198
女兒父親鉤引電影 瀏覽:174
大香蕉手機 瀏覽:856
安卓部落沖突伺服器地址 瀏覽:324
唐古拉優選app叫什麼名字 瀏覽:38
打開一個文件夾為什麼接著就退出 瀏覽:50
女主高中就懷孕的小說 瀏覽:10
app為什麼必須要獲取手機號碼 瀏覽:58
實用的網頁編程 瀏覽:424
寶雞小程序定製開發源碼 瀏覽:432
十大軍事歷史穿越小說 瀏覽:56