导航:首页 > 源码编译 > 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源码相关的资料

热点内容
帝国神话组建云服务器 浏览:825
邓散木pdf 浏览:197
方舟怎么直连服务器图片教程 浏览:561
假相pdf 浏览:334
找对象找程序员怎么找 浏览:976
怎么投诉苹果商店app 浏览:470
华为手机如何看有多少个app 浏览:734
btr如何管理别的服务器 浏览:410
spwm软件算法 浏览:184
70多岁单身程序员 浏览:221
高考考前解压拓展训练 浏览:217
用纸做解压玩具不用浇水 浏览:584
谷轮压缩机序列号 浏览:736
牛顿插值法编程 浏览:366
php多用户留言系统 浏览:731
安卓和苹果如何切换流量 浏览:703
怎么知道dns服务器是多少 浏览:976
5995用什么简便算法脱式计算 浏览:918
电脑上如何上小米云服务器地址 浏览:921
手机资料解压密码 浏览:444