导航:首页 > 源码编译 > 安卓socket源码

安卓socket源码

发布时间:2022-08-17 05:39:49

① 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 块

}
}

}
}

② 在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;
}

}

③ C# socket 聊天的 C/s程序 源码

//"开始"按钮事件
privatevoidbutton1_Click(objectsender,System.EventArgse){
//取得预保存的文件名
stringfileName=textBox3.Text.Trim();
//远程主机
stringhostName=textBox1.Text.Trim();
//端口
intport=Int32.Parse(textBox2.Text.Trim());
//得到主机信息
IPHostEntryipInfo=Dns.GetHostByName(hostName);
//取得IPAddress[]
IPAddress[]ipAddr=ipInfo.AddressList;
//得到ip
IPAddressip=ipAddr[0];
//组合出远程终结点
IPEndPointhostEP=newIPEndPoint(ip,port);
//创建Socket实例
Socketsocket=newSocket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
try
{
//尝试连接
socket.Connect(hostEP);
}
catch(Exceptionse)
{
MessageBox.Show("连接错误"+se.Message,"提示信息
,MessageBoxButtons.RetryCancel,MessageBoxIcon.Information);
}
//发送给远程主机的请求内容串
stringsendStr="GET/HTTP/1.1 Host:"+hostName+
" Connection:Close ";
//创建bytes字节数组以转换发送串
byte[]bytesSendStr=newbyte[1024];
//将发送内容字符串转换成字节byte数组
bytesSendStr=Encoding.ASCII.GetBytes(sendStr);
try
{
//向主机发送请求
socket.Send(bytesSendStr,bytesSendStr.Length,0);
}
catch(Exceptionce)
{
MessageBox.Show("发送错误:"+ce.Message,"提示信息
,MessageBoxButtons.RetryCancel,MessageBoxIcon.Information);
}
//声明接收返回内容的字符串
stringrecvStr="";
//声明字节数组,一次接收数据的长度为1024字节
byte[]recvBytes=newbyte[1024];
//返回实际接收内容的字节数
intbytes=0;
//循环读取,直到接收完所有数据
while(true)
{
bytes=socket.Receive(recvBytes,recvBytes.Length,0);
//读取完成后退出循环
if(bytes〈=0)
break;
//将读取的字节数转换为字符串
recvStr+=Encoding.ASCII.GetString(recvBytes,0,bytes);
}
//将所读取的字符串转换为字节数组
byte[]content=Encoding.ASCII.GetBytes(recvStr);
try
{
//创建文件流对象实例
FileStreamfs=newFileStream(fileName,FileMode.OpenOrCreate,FileAccess.ReadWrite);
//写入文件
fs.Write(content,0,content.Length);
}
catch(Exceptionfe)
{
MessageBox.Show("文件创建/写入错误:"+fe.Message,"提示信息",MessageBoxButtons.RetryCancel,MessageBoxIcon.Information);
}
//禁用Socket
socket.Shutdown(SocketShutdown.Both);
//关闭Socket
socket.Close();
}
}



④ android socket 编程,用java可以实现的服务器端,现在要复制源码到android平台上,可跟客户端连不上

因为你把连接都写在了主线程中,主线程的操作不能超过5秒,否则就报错了,所以你需要在button的点击事件中另开一个线程去做连接的操作,这样就不会出现错误了

⑤ 兄弟。能发下Android 通过Socket与PC(服务端)通信 的完成源代码,收到!给分。

这个实验我是用两台pc做的实验,没有用真机,用的是emule,总体效果感觉可以
大致的思路是这样的
socket的通信分两种一种是 tcp另一种是udp,这个之间的通信方式我就不多说了,
主要的重点是权限的android.premisson,INTERNET

tcp
new Socket();
......

udp
new DatagramSocket();
......

⑥ 您的 安卓基于wifi的对讲机用的是UDPsocket传输的 源码可以发给我嘛 包括xml文件 非常感谢82254887

额。。现在给不了了。。我的笔记本被偷了。。所有的资料都丢了。。。界面很简单,你看到的那个代码就是全部的,里面声明的部件就是全部的界面部件,貌似就两个editview,开始按钮,结束按钮,和退出按钮(我忘了)。。。当时我也是在学习而已。。再有就是配置AndroidManifest.xml,只记得配置了网络权限,还有audio权限。。还有什么就忘了。。不好意思,帮不了你了

⑦ android服务端与电脑pc上c++的客户端 实现socket通信

1、android上的服务器分两种:
① 用 java 写的,这种比较简单,但是需要注意的它的代码已经被转换成了大端了,pc上用c++写传结构体;
② 用 c/c++ 写的,这种方式进行和pc上的通信比较的方便,客户端和服务器段可以都通过结构来传递,唯一需要考虑的是字节对其的问题,可以用两个预处理指令(可以跨平台的)处理;
2、源码的话,我虽然有但是属于公司的项目代码,不方便的;
我是ndk吧的吧主,希望大家关注一下ndk吧,有问题的话也可以到里面留言哦,ndk吧的链接:
http://tieba..com/f?kw=ndk 谢谢!

⑧ 如何用socket实现android手机与手机之间的通信

参考一般的JAVA的socket编程,如果通过手机网络,就不要使用UDP即可。

⑨ 有没有安卓的socket编程的相关资料和源代码,还有相关书籍,麻烦给推荐下

《疯狂Android讲义》这部书非常好。
有源代码,而且讲解也比较透彻。
如果有有一定java基础,懂得一些XML的学习效果会更好。

阅读全文

与安卓socket源码相关的资料

热点内容
安卓登ins需要什么 浏览:835
机器人算法的难点 浏览:225
全自动化编程 浏览:725
程序员高薪限制 浏览:692
压缩图片压缩 浏览:75
美国发明解压魔方 浏览:301
电脑怎么备案网上服务器 浏览:514
旅行商问题Python写法 浏览:952
解压破坏王里面的所有兑换码 浏览:860
文件夹如何拖拽还保留原来的 浏览:22
职业生涯pdf 浏览:954
ubuntu安装软件php 浏览:159
黑马程序员退学流程 浏览:362
网页服务器崩溃怎么回事 浏览:651
cnc编程前景怎么样 浏览:320
lniux命令详解 浏览:495
linuxmysql查询日志 浏览:369
老捷达伙伴压缩比 浏览:94
改后缀加密 浏览:433
邮局选址问题算法 浏览:16